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;
139 static char *action_script = NULL;
148 } command = DAEMON_RUN;
150 typedef enum CalloutEvent {
158 static const char * const callout_event_table[CALLOUT_MAX] = {
159 [CALLOUT_BIND] = "BIND",
160 [CALLOUT_CONFLICT] = "CONFLICT",
161 [CALLOUT_UNBIND] = "UNBIND",
162 [CALLOUT_STOP] = "STOP"
165 typedef struct CalloutEventInfo {
171 #define RANDOM_DEVICE "/dev/urandom"
173 #define DEBUG(x) do {\
179 static void init_rand_seed(void) {
183 /* Try to initialize seed from /dev/urandom, to make it a little
184 * less predictable, and to make sure that multiple machines
185 * booted at the same time choose different random seeds. */
186 if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
187 read(fd, &seed, sizeof(seed));
191 /* If the initialization failed by some reason, we add the time to the seed */
192 seed ^= (unsigned) time(NULL);
197 static uint32_t pick_addr(uint32_t old_addr) {
201 unsigned r = (unsigned) rand();
203 /* Reduce to 16 bits */
205 r = (r >> 16) ^ (r & 0xFFFF);
207 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
209 } while (addr == old_addr || !is_ll_address(addr));
214 static int load_address(const char *fn, uint32_t *addr) {
221 if (!(f = fopen(fn, "r"))) {
223 if (errno == ENOENT) {
228 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
232 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
233 daemon_log(LOG_ERR, "Parse failure");
239 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
249 static int save_address(const char *fn, uint32_t addr) {
257 if (!(f = fopen(fn, "w"))) {
258 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
263 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
278 * Allocate a buffer with two pointers in front, one of which is
279 * guaranteed to point ETHER_HDR_SIZE bytes into it.
281 static ArpPacket* packet_new(size_t packet_len) {
285 assert(packet_len > 0);
288 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
290 p->ether_header = NULL;
291 p->ether_payload = b + sizeof(struct ArpPacket);
294 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
296 p->ether_header = b + sizeof(struct ArpPacket);
297 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
303 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
308 assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
309 assert(packet_len != NULL);
311 *packet_len = ARP_PACKET_SIZE;
312 p = packet_new(*packet_len);
313 r = p->ether_payload;
315 r[1] = 1; /* HTYPE */
316 r[2] = 8; /* PTYPE */
317 r[4] = ETHER_ADDRLEN; /* HLEN */
319 r[7] = (uint8_t) info->operation;
321 memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
322 memcpy(r+14, &info->sender_ip_address, 4);
323 memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
324 memcpy(r+24, &info->target_ip_address, 4);
329 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
332 memset(&info, 0, sizeof(info));
333 info.operation = ARP_REQUEST;
334 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
335 info.target_ip_address = ip_address;
337 return packet_new_with_info(&info, packet_len);
340 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
343 memset(&info, 0, sizeof(info));
344 info.operation = ARP_REQUEST;
345 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
346 info.target_ip_address = ip_address;
347 info.sender_ip_address = ip_address;
349 return packet_new_with_info(&info, packet_len);
352 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
356 p = (uint8_t *)packet->ether_payload;
359 if (packet_len < ARP_PACKET_SIZE)
362 /* Check HTYPE and PTYPE */
363 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
366 /* Check HLEN, PLEN, OPERATION */
367 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
370 info->operation = p[7];
371 memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
372 memcpy(&info->sender_ip_address, p+14, 4);
373 memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
374 memcpy(&info->target_ip_address, p+24, 4);
379 static void set_state(State st, int reset_counter, uint32_t address) {
380 static const char* const state_table[] = {
381 [STATE_START] = "START",
382 [STATE_WAITING_PROBE] = "WAITING_PROBE",
383 [STATE_PROBING] = "PROBING",
384 [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
385 [STATE_ANNOUNCING] = "ANNOUNCING",
386 [STATE_RUNNING] = "RUNNING",
387 [STATE_SLEEPING] = "SLEEPING"
391 assert(st < STATE_MAX);
393 if (st == state && !reset_counter) {
395 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
397 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
402 if (state == STATE_SLEEPING)
403 avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
404 else if (state == STATE_ANNOUNCING)
405 avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
406 else if (state == STATE_RUNNING)
407 avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
409 avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
412 static int interface_up(int iface) {
416 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
417 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
421 memset(&ifreq, 0, sizeof(ifreq));
422 if (!if_indextoname(iface, ifreq.ifr_name)) {
423 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
427 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
428 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
432 ifreq.ifr_flags |= IFF_UP;
434 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
435 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
452 /* Linux 'packet socket' specific implementation */
454 static int open_socket(int iface, uint8_t *hw_address) {
456 struct sockaddr_ll sa;
459 if (interface_up(iface) < 0)
462 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
463 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
467 memset(&sa, 0, sizeof(sa));
468 sa.sll_family = AF_PACKET;
469 sa.sll_protocol = htons(ETH_P_ARP);
470 sa.sll_ifindex = iface;
472 if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
473 daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
478 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
479 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
483 if (sa.sll_halen != ETHER_ADDRLEN) {
484 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
488 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
499 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
500 struct sockaddr_ll sa;
504 assert(packet_len > 0);
506 memset(&sa, 0, sizeof(sa));
507 sa.sll_family = AF_PACKET;
508 sa.sll_protocol = htons(ETH_P_ARP);
509 sa.sll_ifindex = iface;
510 sa.sll_halen = ETHER_ADDRLEN;
511 memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
513 if (sendto(fd, packet, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
514 daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
521 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
523 struct sockaddr_ll sa;
533 if (ioctl(fd, FIONREAD, &s) < 0) {
534 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
541 *packet = packet_new(s);
544 if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
545 daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
549 *packet_len = (size_t) r;
563 close_socket(int fd) {
567 #else /* !__linux__ */
568 /* PCAP-based implementation */
571 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
572 static uint8_t __lladdr[ETHER_ADDRLEN];
575 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
579 __get_ether_addr(int ifindex, u_char *lladdr)
583 struct if_msghdr *ifm;
586 struct sockaddr_dl *sdl;
593 mib[4] = NET_RT_IFLIST;
596 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
597 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
604 daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
608 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
609 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
616 for (next = buf; next < lim; next += ifm->ifm_msglen) {
617 ifm = (struct if_msghdr *)next;
618 if (ifm->ifm_type == RTM_IFINFO) {
619 sdl = (struct sockaddr_dl *)(ifm + 1);
620 memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
629 open_socket(int iface, uint8_t *hw_address)
631 struct bpf_program bpf;
632 char ifname[IFNAMSIZ];
637 assert(__pp == NULL);
639 if (interface_up(iface) < 0) {
642 if (__get_ether_addr(iface, __lladdr) == -1) {
645 if (if_indextoname(iface, ifname) == NULL) {
649 pp = pcap_open_live(ifname, 1500, 0, 0, __pcap_errbuf);
653 err = pcap_set_datalink(pp, DLT_EN10MB);
655 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
659 err = pcap_setdirection(pp, PCAP_D_IN);
661 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
666 fd = pcap_get_selectable_fd(pp);
672 /* XXX: can we use this with pcap_next_ex() ? */
673 err = pcap_setnonblock(pp, 1, __pcap_errbuf);
680 err = pcap_compile(pp, &bpf,
681 "arp and ether dst ff:ff:ff:ff:ff:ff", 1, 0);
683 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
687 err = pcap_setfilter(pp, &bpf);
689 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
695 /* Stash pcap-specific context away. */
696 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
703 close_socket(int fd __unused)
706 assert(__pp != NULL);
712 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
713 * and prepend the required ethernet header information before sending.
716 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
719 struct ether_header *eh;
721 assert(__pp != NULL);
722 assert(packet != NULL);
724 eh = (struct ether_header *)packet->ether_header;
725 memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
726 memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
727 eh->ether_type = htons(0x0806);
729 return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
733 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
735 struct pcap_pkthdr *ph;
741 assert(__pp != NULL);
742 assert(packet != NULL);
743 assert(packet_len != NULL);
749 err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
750 if (err == 1 && ph->caplen <= ph->len) {
751 ap = packet_new(ph->caplen);
752 memcpy(ap->ether_header, pd, ph->caplen);
754 *packet_len = (ph->caplen - sizeof(struct ether_header));
758 daemon_log(LOG_ERR, "pcap len > caplen");
760 daemon_log(LOG_ERR, "pcap_next_ex: %s",
767 #endif /* __linux__ */
769 int is_ll_address(uint32_t addr) {
771 ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
772 ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
773 ((ntohl(addr) & 0x0000FF00) != 0xFF00);
776 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
779 gettimeofday(tv, NULL);
782 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
785 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
790 static FILE* fork_dispatcher(void) {
796 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
800 if ((pid = fork()) < 0)
806 /* Please note that the signal pipe is not closed at this
807 * point, signals will thus be dispatched in the main
810 daemon_retval_done();
814 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
818 if (!(f = fdopen(fds[0], "r"))) {
819 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
820 goto dispatcher_fail;
824 CalloutEventInfo info;
825 char name[IFNAMSIZ], buf[64];
828 if (fread(&info, sizeof(info), 1, f) != 1) {
832 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
833 goto dispatcher_fail;
836 assert(info.event <= CALLOUT_MAX);
838 if (!if_indextoname(info.ifindex, name)) {
839 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
843 if (daemon_exec("/", &k,
844 action_script, action_script,
845 callout_event_table[info.event],
847 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
849 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
854 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
865 /* If the main process is trapped inside a chroot() we have to
866 * remove the PID file for it */
868 if (!no_chroot && wrote_pid_file)
869 daemon_pid_file_remove();
880 if (!(ret = fdopen(fds[1], "w"))) {
881 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
896 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
897 CalloutEventInfo info;
898 char buf[64], ifname[IFNAMSIZ];
900 daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
901 callout_event_table[event],
902 inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
903 if_indextoname(iface, ifname));
906 info.ifindex = iface;
909 if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
910 daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
917 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
919 static int drop_privs(void) {
928 /* Get user/group ID */
932 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
933 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
937 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
938 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
942 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);
945 /* Create directory */
947 r = mkdir(AVAHI_IPDATA_DIR, 0755);
950 if (r < 0 && errno != EEXIST) {
951 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
955 /* Convey working directory */
960 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
962 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
963 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
967 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
968 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
976 if (chroot(AVAHI_IPDATA_DIR) < 0) {
977 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
981 daemon_log(LOG_INFO, "Successfully called chroot().");
984 /* Since we are now trapped inside a chroot we cannot remove
985 * the pid file anymore, the helper process will do that for us. */
993 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
994 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
998 #if defined(HAVE_SETRESGID)
999 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1000 #elif defined(HAVE_SETEGID)
1001 if ((r = setgid(gr->gr_gid)) >= 0)
1002 r = setegid(gr->gr_gid);
1003 #elif defined(HAVE_SETREGID)
1004 r = setregid(gr->gr_gid, gr->gr_gid);
1006 #error "No API to drop priviliges"
1010 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1014 #if defined(HAVE_SETRESUID)
1015 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1016 #elif defined(HAVE_SETEUID)
1017 if ((r = setuid(pw->pw_uid)) >= 0)
1018 r = seteuid(pw->pw_uid);
1019 #elif defined(HAVE_SETREUID)
1020 r = setreuid(pw->pw_uid, pw->pw_uid);
1022 #error "No API to drop priviliges"
1026 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1030 set_env("USER", pw->pw_name);
1031 set_env("LOGNAME", pw->pw_name);
1032 set_env("HOME", pw->pw_dir);
1034 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1040 static int loop(int iface, uint32_t addr) {
1048 int fd = -1, ret = -1;
1049 struct timeval next_wakeup;
1050 int next_wakeup_valid = 0;
1052 ArpPacket *in_packet = NULL;
1053 size_t in_packet_len;
1054 ArpPacket *out_packet = NULL;
1055 size_t out_packet_len;
1056 uint8_t hw_address[ETHER_ADDRLEN];
1057 struct pollfd pollfds[FD_MAX];
1059 Event event = EVENT_NULL;
1060 int retval_sent = !daemonize;
1062 FILE *dispatcher = NULL;
1063 char *address_fn = NULL;
1066 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1068 if (!(dispatcher = fork_dispatcher()))
1071 if ((fd = open_socket(iface, hw_address)) < 0)
1074 if ((iface_fd = iface_init(iface)) < 0)
1077 if (drop_privs() < 0)
1082 else if (iface_get_initial_state(&st) < 0)
1090 p = AVAHI_IPDATA_DIR;
1092 address_fn = avahi_strdup_printf(
1093 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1094 hw_address[0], hw_address[1],
1095 hw_address[2], hw_address[3],
1096 hw_address[4], hw_address[5]);
1099 load_address(address_fn, &addr);
1101 if (addr && !is_ll_address(addr)) {
1102 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)));
1110 for (i = 0; i < ETHER_ADDRLEN; i++)
1111 a += hw_address[i]*i;
1113 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1116 set_state(st, 1, addr);
1118 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1120 if (state == STATE_SLEEPING)
1121 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1123 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1124 daemon_retval_send(0);
1128 memset(pollfds, 0, sizeof(pollfds));
1129 pollfds[FD_ARP].fd = fd;
1130 pollfds[FD_ARP].events = POLLIN;
1131 pollfds[FD_IFACE].fd = iface_fd;
1132 pollfds[FD_IFACE].events = POLLIN;
1133 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1134 pollfds[FD_SIGNAL].events = POLLIN;
1140 if (state == STATE_START) {
1142 /* First, wait a random time */
1143 set_state(STATE_WAITING_PROBE, 1, addr);
1145 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1146 next_wakeup_valid = 1;
1148 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1149 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1152 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1153 set_state(STATE_PROBING, 0, addr);
1155 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1156 next_wakeup_valid = 1;
1158 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1160 /* Send the last probe */
1161 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1162 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1164 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1165 next_wakeup_valid = 1;
1167 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1168 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1170 /* Send announcement packet */
1171 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1172 set_state(STATE_ANNOUNCING, 0, addr);
1174 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1175 next_wakeup_valid = 1;
1177 if (n_iteration == 0) {
1178 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1184 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1186 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1187 set_state(STATE_RUNNING, 0, addr);
1189 next_wakeup_valid = 0;
1191 save_address(address_fn, addr);
1194 daemon_retval_send(0);
1198 } else if (event == EVENT_PACKET) {
1203 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1204 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1208 if (info.sender_ip_address == addr) {
1209 /* Normal conflict */
1211 daemon_log(LOG_INFO, "Recieved conflicting normal ARP packet.");
1212 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1213 /* Probe conflict */
1214 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1217 daemon_log(LOG_INFO, "Recieved conflicting probe ARP packet.");
1222 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1223 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1226 /* Pick a new address */
1227 addr = pick_addr(addr);
1229 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1233 set_state(STATE_WAITING_PROBE, 1, addr);
1235 if (n_conflict >= MAX_CONFLICTS) {
1236 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1237 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1239 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1241 next_wakeup_valid = 1;
1243 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1246 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED) {
1248 daemon_log(LOG_INFO, "A routable address has been configured.");
1250 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1251 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1255 daemon_retval_send(0);
1259 set_state(STATE_SLEEPING, 1, addr);
1260 next_wakeup_valid = 0;
1262 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1264 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1266 set_state(STATE_WAITING_PROBE, 1, addr);
1268 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1269 next_wakeup_valid = 1;
1271 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING && !force_bind) {
1273 /* The user requested a reannouncing of the address by a SIGHUP */
1274 daemon_log(LOG_INFO, "Reannouncing address.");
1276 /* Send announcement packet */
1277 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1278 set_state(STATE_ANNOUNCING, 1, addr);
1280 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1281 next_wakeup_valid = 1;
1285 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1287 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1290 avahi_free(out_packet);
1295 avahi_free(in_packet);
1302 if (next_wakeup_valid) {
1303 usec = avahi_age(&next_wakeup);
1304 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1307 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1309 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1313 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1315 } else if (r == 0) {
1316 event = EVENT_TIMEOUT;
1317 next_wakeup_valid = 0;
1321 if (pollfds[FD_ARP].revents) {
1323 if (pollfds[FD_ARP].revents == POLLERR) {
1324 /* The interface is probably down, let's recreate our socket */
1328 if ((fd = open_socket(iface, hw_address)) < 0)
1331 pollfds[FD_ARP].fd = fd;
1335 assert(pollfds[FD_ARP].revents == POLLIN);
1337 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1341 event = EVENT_PACKET;
1345 if (event == EVENT_NULL &&
1346 pollfds[FD_IFACE].revents) {
1348 assert(pollfds[FD_IFACE].revents == POLLIN);
1350 if (iface_process(&event) < 0)
1354 if (event == EVENT_NULL &&
1355 pollfds[FD_SIGNAL].revents) {
1358 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1360 if ((sig = daemon_signal_next()) <= 0) {
1361 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1368 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1373 waitpid(-1, NULL, WNOHANG);
1377 event = EVENT_REFRESH_REQUEST;
1389 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1390 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1392 avahi_free(out_packet);
1393 avahi_free(in_packet);
1401 if (daemonize && !retval_sent)
1402 daemon_retval_send(ret);
1408 avahi_free(address_fn);
1414 static void help(FILE *f, const char *a0) {
1416 "%s [options] INTERFACE\n"
1417 " -h --help Show this help\n"
1418 " -D --daemonize Daemonize after startup\n"
1419 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1420 " -k --kill Kill a running daemon\n"
1421 " -r --refresh Request a running daemon to refresh it's IP address\n"
1422 " -c --check Return 0 if a daemon is already running\n"
1423 " -V --version Show version\n"
1424 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1426 " -t --script=script Action script to run (defaults to\n"
1427 " /etc/avahi/avahi-autoipd.action)\n"
1428 " -w --wait Wait until an address has been acquired before\n"
1430 " --force-bind Assign an IPv4LL address even if a routable address\n"
1431 " is already assigned\n"
1432 " --no-drop-root Don't drop privileges\n"
1434 " --no-chroot Don't chroot()\n"
1436 " --no-proc-title Don't modify process title\n"
1437 " --debug Increase verbosity\n",
1441 static int parse_command_line(int argc, char *argv[]) {
1445 OPTION_NO_PROC_TITLE = 256,
1448 OPTION_NO_DROP_ROOT,
1454 static const struct option long_options[] = {
1455 { "help", no_argument, NULL, 'h' },
1456 { "daemonize", no_argument, NULL, 'D' },
1457 { "syslog", no_argument, NULL, 's' },
1458 { "kill", no_argument, NULL, 'k' },
1459 { "refresh", no_argument, NULL, 'r' },
1460 { "check", no_argument, NULL, 'c' },
1461 { "version", no_argument, NULL, 'V' },
1462 { "start", required_argument, NULL, 'S' },
1463 { "script", required_argument, NULL, 't' },
1464 { "wait", no_argument, NULL, 'w' },
1465 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1466 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1468 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1470 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1471 { "debug", no_argument, NULL, OPTION_DEBUG },
1472 { NULL, 0, NULL, 0 }
1475 while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1482 command = DAEMON_HELP;
1488 command = DAEMON_KILL;
1491 command = DAEMON_VERSION;
1494 command = DAEMON_REFRESH;
1497 command = DAEMON_CHECK;
1501 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1502 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1507 avahi_free(action_script);
1508 action_script = avahi_strdup(optarg);
1511 wait_for_address = 1;
1514 case OPTION_NO_PROC_TITLE:
1515 modify_proc_title = 0;
1522 case OPTION_FORCE_BIND:
1526 case OPTION_NO_DROP_ROOT:
1531 case OPTION_NO_CHROOT:
1541 if (command == DAEMON_RUN ||
1542 command == DAEMON_KILL ||
1543 command == DAEMON_REFRESH ||
1544 command == DAEMON_CHECK) {
1546 if (optind >= argc) {
1547 fprintf(stderr, "Missing interface name.\n");
1551 interface_name = avahi_strdup(argv[optind++]);
1554 if (optind != argc) {
1555 fprintf(stderr, "Too many arguments\n");
1560 action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1565 static const char* pid_file_proc(void) {
1566 return pid_file_name;
1569 int main(int argc, char*argv[]) {
1571 char *log_ident = NULL;
1573 signal(SIGPIPE, SIG_IGN);
1575 if ((argv0 = strrchr(argv[0], '/')))
1576 argv0 = avahi_strdup(argv0 + 1);
1578 argv0 = avahi_strdup(argv[0]);
1580 daemon_log_ident = argv0;
1582 if (parse_command_line(argc, argv) < 0)
1585 if (modify_proc_title)
1586 avahi_init_proc_title(argc, argv);
1588 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1589 daemon_pid_file_proc = pid_file_proc;
1590 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1592 if (command == DAEMON_RUN) {
1598 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1599 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1603 if (getuid() != 0) {
1604 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1608 if ((pid = daemon_pid_file_is_running()) >= 0) {
1609 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1614 daemon_retval_init();
1616 if ((pid = daemon_fork()) < 0)
1618 else if (pid != 0) {
1622 if ((ret = daemon_retval_wait(20)) < 0) {
1623 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1634 if (use_syslog || daemonize)
1635 daemon_log_use = DAEMON_LOG_SYSLOG;
1639 if (daemon_pid_file_create() < 0) {
1640 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1643 daemon_retval_send(1);
1648 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1650 if (loop(ifindex, start_address) < 0)
1654 } else if (command == DAEMON_HELP) {
1655 help(stdout, argv0);
1658 } else if (command == DAEMON_VERSION) {
1659 printf("%s "PACKAGE_VERSION"\n", argv0);
1662 } else if (command == DAEMON_KILL) {
1663 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1664 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1669 } else if (command == DAEMON_REFRESH) {
1670 if (daemon_pid_file_kill(SIGHUP) < 0) {
1671 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1676 } else if (command == DAEMON_CHECK)
1677 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1683 daemon_retval_done();
1686 daemon_pid_file_remove();
1688 avahi_free(log_ident);
1689 avahi_free(pid_file_name);
1691 avahi_free(interface_name);
1692 avahi_free(action_script);