2 This file is part of avahi.
4 avahi is free software; you can redistribute it and/or modify it
5 under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 avahi is distributed in the hope that it will be useful, but WITHOUT
10 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
12 Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with avahi; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24 #include <sys/param.h>
25 #include <sys/types.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/sysctl.h>
35 #include <netpacket/packet.h>
37 #include <net/ethernet.h>
40 #include <net/if_dl.h>
41 #include <net/route.h>
43 #include <arpa/inet.h>
64 /* Old versions of PCAP defined it as D_IN */
66 #define PCAP_D_IN D_IN
71 #include <avahi-common/malloc.h>
72 #include <avahi-common/timeval.h>
73 #include <avahi-daemon/setproctitle.h>
75 #include <libdaemon/dfork.h>
76 #include <libdaemon/dsignal.h>
77 #include <libdaemon/dlog.h>
78 #include <libdaemon/dpid.h>
79 #include <libdaemon/dexec.h>
84 /* An implementation of RFC 3927 */
86 /* Constants from the RFC */
91 #define ANNOUNCE_WAIT 2
92 #define ANNOUNCE_NUM 2
93 #define ANNOUNCE_INTERVAL 2
94 #define MAX_CONFLICTS 10
95 #define RATE_LIMIT_INTERVAL 60
96 #define DEFEND_INTERVAL 10
98 #define IPV4LL_NETWORK 0xA9FE0000L
99 #define IPV4LL_NETMASK 0xFFFF0000L
100 #define IPV4LL_HOSTMASK 0x0000FFFFL
101 #define IPV4LL_BROADCAST 0xA9FEFFFFL
103 #define ETHER_ADDRLEN 6
104 #define ETHER_HDR_SIZE (2+2*ETHER_ADDRLEN)
105 #define ARP_PACKET_SIZE (8+4+4+2*ETHER_ADDRLEN)
107 typedef enum ArpOperation {
112 typedef struct ArpPacketInfo {
113 ArpOperation operation;
115 uint32_t sender_ip_address, target_ip_address;
116 uint8_t sender_hw_address[ETHER_ADDRLEN], target_hw_address[ETHER_ADDRLEN];
119 typedef struct ArpPacket {
120 uint8_t *ether_header;
121 uint8_t *ether_payload;
124 static State state = STATE_START;
125 static int n_iteration = 0;
126 static int n_conflict = 0;
128 static char *interface_name = NULL;
129 static char *pid_file_name = NULL;
130 static uint32_t start_address = 0;
131 static char *argv0 = NULL;
132 static int daemonize = 0;
133 static int wait_for_address = 0;
134 static int use_syslog = 0;
135 static int debug = 0;
136 static int modify_proc_title = 1;
137 static int force_bind = 0;
139 static int no_chroot = 0;
141 static int no_drop_root = 0;
142 static int wrote_pid_file = 0;
143 static char *action_script = NULL;
152 } command = DAEMON_RUN;
154 typedef enum CalloutEvent {
162 static const char * const callout_event_table[CALLOUT_MAX] = {
163 [CALLOUT_BIND] = "BIND",
164 [CALLOUT_CONFLICT] = "CONFLICT",
165 [CALLOUT_UNBIND] = "UNBIND",
166 [CALLOUT_STOP] = "STOP"
169 typedef struct CalloutEventInfo {
175 #define RANDOM_DEVICE "/dev/urandom"
184 static void init_rand_seed(void) {
188 /* Try to initialize seed from /dev/urandom, to make it a little
189 * less predictable, and to make sure that multiple machines
190 * booted at the same time choose different random seeds. */
191 if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
192 read(fd, &seed, sizeof(seed));
196 /* If the initialization failed by some reason, we add the time to the seed */
197 seed ^= (unsigned) time(NULL);
202 static uint32_t pick_addr(uint32_t old_addr) {
206 unsigned r = (unsigned) rand();
208 /* Reduce to 16 bits */
210 r = (r >> 16) ^ (r & 0xFFFF);
212 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
214 } while (addr == old_addr || !is_ll_address(addr));
219 static int load_address(const char *fn, uint32_t *addr) {
226 if (!(f = fopen(fn, "r"))) {
228 if (errno == ENOENT) {
233 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
237 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
238 daemon_log(LOG_ERR, "Parse failure");
244 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
254 static int save_address(const char *fn, uint32_t addr) {
262 if (!(f = fopen(fn, "w"))) {
263 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
268 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
283 * Allocate a buffer with two pointers in front, one of which is
284 * guaranteed to point ETHER_HDR_SIZE bytes into it.
286 static ArpPacket* packet_new(size_t packet_len) {
290 assert(packet_len > 0);
293 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
295 p->ether_header = NULL;
296 p->ether_payload = b + sizeof(struct ArpPacket);
299 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
301 p->ether_header = b + sizeof(struct ArpPacket);
302 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
308 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
313 assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
314 assert(packet_len != NULL);
316 *packet_len = ARP_PACKET_SIZE;
317 p = packet_new(*packet_len);
318 r = p->ether_payload;
320 r[1] = 1; /* HTYPE */
321 r[2] = 8; /* PTYPE */
322 r[4] = ETHER_ADDRLEN; /* HLEN */
324 r[7] = (uint8_t) info->operation;
326 memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
327 memcpy(r+14, &info->sender_ip_address, 4);
328 memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
329 memcpy(r+24, &info->target_ip_address, 4);
334 static ArpPacket *packet_new_probe(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;
342 return packet_new_with_info(&info, packet_len);
345 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
348 memset(&info, 0, sizeof(info));
349 info.operation = ARP_REQUEST;
350 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
351 info.target_ip_address = ip_address;
352 info.sender_ip_address = ip_address;
354 return packet_new_with_info(&info, packet_len);
357 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
361 p = (uint8_t *)packet->ether_payload;
364 if (packet_len < ARP_PACKET_SIZE)
367 /* Check HTYPE and PTYPE */
368 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
371 /* Check HLEN, PLEN, OPERATION */
372 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
375 info->operation = p[7];
376 memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
377 memcpy(&info->sender_ip_address, p+14, 4);
378 memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
379 memcpy(&info->target_ip_address, p+24, 4);
384 static void set_state(State st, int reset_counter, uint32_t address) {
385 static const char* const state_table[] = {
386 [STATE_START] = "START",
387 [STATE_WAITING_PROBE] = "WAITING_PROBE",
388 [STATE_PROBING] = "PROBING",
389 [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
390 [STATE_ANNOUNCING] = "ANNOUNCING",
391 [STATE_RUNNING] = "RUNNING",
392 [STATE_SLEEPING] = "SLEEPING"
396 assert(st < STATE_MAX);
398 if (st == state && !reset_counter) {
400 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
402 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
407 if (state == STATE_SLEEPING)
408 avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
409 else if (state == STATE_ANNOUNCING)
410 avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
411 else if (state == STATE_RUNNING)
412 avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
414 avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
417 static int interface_up(int iface) {
421 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
422 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
426 memset(&ifreq, 0, sizeof(ifreq));
427 if (!if_indextoname(iface, ifreq.ifr_name)) {
428 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
432 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
433 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
437 ifreq.ifr_flags |= IFF_UP;
439 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
440 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
457 /* Linux 'packet socket' specific implementation */
459 static int open_socket(int iface, uint8_t *hw_address) {
461 struct sockaddr_ll sa;
464 if (interface_up(iface) < 0)
467 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
468 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
472 memset(&sa, 0, sizeof(sa));
473 sa.sll_family = AF_PACKET;
474 sa.sll_protocol = htons(ETH_P_ARP);
475 sa.sll_ifindex = iface;
477 if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
478 daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
483 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
484 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
488 if (sa.sll_halen != ETHER_ADDRLEN) {
489 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
493 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
504 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
505 struct sockaddr_ll sa;
509 assert(packet_len > 0);
511 memset(&sa, 0, sizeof(sa));
512 sa.sll_family = AF_PACKET;
513 sa.sll_protocol = htons(ETH_P_ARP);
514 sa.sll_ifindex = iface;
515 sa.sll_halen = ETHER_ADDRLEN;
516 memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
518 if (sendto(fd, packet->ether_payload, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
519 daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
526 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
528 struct sockaddr_ll sa;
538 if (ioctl(fd, FIONREAD, &s) < 0) {
539 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
546 *packet = packet_new(s);
549 if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
550 daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
554 *packet_len = (size_t) r;
567 static void close_socket(int fd) {
571 #else /* !__linux__ */
572 /* PCAP-based implementation */
575 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
576 static uint8_t __lladdr[ETHER_ADDRLEN];
579 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
582 static int __get_ether_addr(int ifindex, u_char *lladdr) {
585 struct if_msghdr *ifm;
588 struct sockaddr_dl *sdl;
595 mib[4] = NET_RT_IFLIST;
598 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
599 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
604 buf = avahi_malloc(len);
605 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
606 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
613 for (next = buf; next < lim; next += ifm->ifm_msglen) {
614 ifm = (struct if_msghdr *)next;
615 if (ifm->ifm_type == RTM_IFINFO) {
616 sdl = (struct sockaddr_dl *)(ifm + 1);
617 memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
625 #define PCAP_TIMEOUT 500 /* 0.5s */
627 static int open_socket(int iface, uint8_t *hw_address) {
628 struct bpf_program bpf;
630 char ifname[IFNAMSIZ];
635 assert(__pp == NULL);
637 if (interface_up(iface) < 0)
640 if (__get_ether_addr(iface, __lladdr) == -1)
643 if (if_indextoname(iface, ifname) == NULL)
647 * Using a timeout for BPF is fairly portable across BSDs. On most
648 * modern versions, using the timeout/nonblock/poll method results in
649 * fairly sane behavior, with the timeout only coming into play during
650 * the next_ex() call itself (so, for us, that's only when there's
651 * data). On older versions, it may result in a PCAP_TIMEOUT busy-wait
652 * on some versions, though, as the poll() may terminate at the
653 * PCAP_TIMEOUT instead of the poll() timeout.
655 pp = pcap_open_live(ifname, 1500, 0, PCAP_TIMEOUT, __pcap_errbuf);
659 err = pcap_set_datalink(pp, DLT_EN10MB);
661 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
665 err = pcap_setdirection(pp, PCAP_D_IN);
667 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
672 fd = pcap_get_selectable_fd(pp);
679 * Using setnonblock is a portability stop-gap. Using the timeout in
680 * combination with setnonblock will ensure on most BSDs that the
681 * next_ex call returns in a timely fashion.
683 err = pcap_setnonblock(pp, 1, __pcap_errbuf);
689 filter = avahi_strdup_printf("arp and (ether dst ff:ff:ff:ff:ff:ff or "
690 "%02x:%02x:%02x:%02x:%02x:%02x)",
691 __lladdr[0], __lladdr[1],
692 __lladdr[2], __lladdr[3],
693 __lladdr[4], __lladdr[5]);
694 DEBUG(daemon_log(LOG_DEBUG, "Using pcap filter '%s'", filter));
696 err = pcap_compile(pp, &bpf, filter, 1, 0);
699 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
703 err = pcap_setfilter(pp, &bpf);
705 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
711 /* Stash pcap-specific context away. */
712 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
718 static void close_socket(int fd AVAHI_GCC_UNUSED) {
719 assert(__pp != NULL);
725 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
726 * and prepend the required ethernet header information before sending.
728 static int send_packet(int fd AVAHI_GCC_UNUSED, int iface AVAHI_GCC_UNUSED, ArpPacket *packet, size_t packet_len) {
729 struct ether_header *eh;
731 assert(__pp != NULL);
732 assert(packet != NULL);
734 eh = (struct ether_header *)packet->ether_header;
735 memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
736 memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
737 eh->ether_type = htons(0x0806);
739 return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
742 static int recv_packet(int fd AVAHI_GCC_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));
764 } else if (err >= 0) {
766 * err == 1: Just drop bogus packets (>1500 for an arp packet!?)
769 * err == 0: We might have had traffic on the pcap fd that
770 * didn't match the filter, in which case we'll get 0 packets.
774 daemon_log(LOG_ERR, "pcap_next_ex(%d): %s",
775 err, pcap_geterr(__pp));
779 #endif /* __linux__ */
781 int is_ll_address(uint32_t addr) {
783 ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
784 ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
785 ((ntohl(addr) & 0x0000FF00) != 0xFF00);
788 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
791 gettimeofday(tv, NULL);
794 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
797 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
802 static FILE* fork_dispatcher(void) {
808 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
812 if ((pid = fork()) < 0)
818 /* Please note that the signal pipe is not closed at this
819 * point, signals will thus be dispatched in the main
822 daemon_retval_done();
824 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
828 if (!(f = fdopen(fds[0], "r"))) {
829 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
830 goto dispatcher_fail;
834 CalloutEventInfo info;
835 char name[IFNAMSIZ], buf[64];
838 if (fread(&info, sizeof(info), 1, f) != 1) {
842 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
843 goto dispatcher_fail;
846 assert(info.event <= CALLOUT_MAX);
848 if (!if_indextoname(info.ifindex, name)) {
849 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
853 if (daemon_exec("/", &k,
854 action_script, action_script,
855 callout_event_table[info.event],
857 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
859 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
864 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
875 /* If the main process is trapped inside a chroot() we have to
876 * remove the PID file for it */
878 if (!no_chroot && wrote_pid_file)
879 daemon_pid_file_remove();
890 if (!(ret = fdopen(fds[1], "w"))) {
891 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
906 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
907 CalloutEventInfo info;
908 char buf[64], ifname[IFNAMSIZ];
910 daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
911 callout_event_table[event],
912 inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
913 if_indextoname(iface, ifname));
916 info.ifindex = iface;
919 if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
920 daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
927 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
929 static int drop_privs(void) {
938 /* Get user/group ID */
942 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
943 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
947 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
948 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
952 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);
955 /* Create directory */
957 r = mkdir(AVAHI_IPDATA_DIR, 0755);
960 if (r < 0 && errno != EEXIST) {
961 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
965 /* Convey working directory */
970 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
972 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
973 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
977 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
978 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
986 if (chroot(AVAHI_IPDATA_DIR) < 0) {
987 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
991 daemon_log(LOG_INFO, "Successfully called chroot().");
994 /* Since we are now trapped inside a chroot we cannot remove
995 * the pid file anymore, the helper process will do that for us. */
1001 if (!no_drop_root) {
1003 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1004 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1008 #if defined(HAVE_SETRESGID)
1009 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1010 #elif defined(HAVE_SETEGID)
1011 if ((r = setgid(gr->gr_gid)) >= 0)
1012 r = setegid(gr->gr_gid);
1013 #elif defined(HAVE_SETREGID)
1014 r = setregid(gr->gr_gid, gr->gr_gid);
1016 #error "No API to drop privileges"
1020 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1024 #if defined(HAVE_SETRESUID)
1025 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1026 #elif defined(HAVE_SETEUID)
1027 if ((r = setuid(pw->pw_uid)) >= 0)
1028 r = seteuid(pw->pw_uid);
1029 #elif defined(HAVE_SETREUID)
1030 r = setreuid(pw->pw_uid, pw->pw_uid);
1032 #error "No API to drop privileges"
1036 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1040 set_env("USER", pw->pw_name);
1041 set_env("LOGNAME", pw->pw_name);
1042 set_env("HOME", pw->pw_dir);
1044 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1050 static int loop(int iface, uint32_t addr) {
1058 int fd = -1, ret = -1;
1059 struct timeval next_wakeup;
1060 int next_wakeup_valid = 0;
1062 ArpPacket *in_packet = NULL;
1063 size_t in_packet_len;
1064 ArpPacket *out_packet = NULL;
1065 size_t out_packet_len;
1066 uint8_t hw_address[ETHER_ADDRLEN];
1067 struct pollfd pollfds[FD_MAX];
1069 Event event = EVENT_NULL;
1070 int retval_sent = !daemonize;
1072 FILE *dispatcher = NULL;
1073 char *address_fn = NULL;
1076 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP, 0);
1078 if (!(dispatcher = fork_dispatcher()))
1081 if ((fd = open_socket(iface, hw_address)) < 0)
1084 if ((iface_fd = iface_init(iface)) < 0)
1087 if (drop_privs() < 0)
1092 else if (iface_get_initial_state(&st) < 0)
1100 p = AVAHI_IPDATA_DIR;
1102 address_fn = avahi_strdup_printf(
1103 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1104 hw_address[0], hw_address[1],
1105 hw_address[2], hw_address[3],
1106 hw_address[4], hw_address[5]);
1109 load_address(address_fn, &addr);
1111 if (addr && !is_ll_address(addr)) {
1112 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)));
1120 for (i = 0; i < ETHER_ADDRLEN; i++)
1121 a += hw_address[i]*i;
1123 a = (a % 0xFE00) + 0x0100;
1125 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1128 assert(is_ll_address(addr));
1130 set_state(st, 1, addr);
1132 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1134 if (state == STATE_SLEEPING)
1135 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1137 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1138 daemon_retval_send(0);
1142 memset(pollfds, 0, sizeof(pollfds));
1143 pollfds[FD_ARP].fd = fd;
1144 pollfds[FD_ARP].events = POLLIN;
1145 pollfds[FD_IFACE].fd = iface_fd;
1146 pollfds[FD_IFACE].events = POLLIN;
1147 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1148 pollfds[FD_SIGNAL].events = POLLIN;
1154 if (state == STATE_START) {
1156 /* First, wait a random time */
1157 set_state(STATE_WAITING_PROBE, 1, addr);
1159 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1160 next_wakeup_valid = 1;
1162 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1163 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1166 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1167 set_state(STATE_PROBING, 0, addr);
1169 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1170 next_wakeup_valid = 1;
1172 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1174 /* Send the last probe */
1175 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1176 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1178 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1179 next_wakeup_valid = 1;
1181 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1182 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1184 /* Send announcement packet */
1185 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1186 set_state(STATE_ANNOUNCING, 0, addr);
1188 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1189 next_wakeup_valid = 1;
1191 if (n_iteration == 0) {
1192 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1198 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1200 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1201 set_state(STATE_RUNNING, 0, addr);
1203 next_wakeup_valid = 0;
1205 save_address(address_fn, addr);
1208 daemon_retval_send(0);
1212 } else if (event == EVENT_PACKET) {
1217 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1218 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1222 if (info.sender_ip_address == addr) {
1224 if (memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN)) {
1225 /* Normal conflict */
1227 daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1229 daemon_log(LOG_DEBUG, "Received ARP packet back on source interface. Ignoring.");
1231 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1232 /* Probe conflict */
1233 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1236 daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1241 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1242 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1245 /* Pick a new address */
1246 addr = pick_addr(addr);
1248 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1252 set_state(STATE_WAITING_PROBE, 1, addr);
1254 if (n_conflict >= MAX_CONFLICTS) {
1255 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1256 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1258 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1260 next_wakeup_valid = 1;
1262 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1265 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED && !force_bind) {
1267 daemon_log(LOG_INFO, "A routable address has been configured.");
1269 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1270 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1274 daemon_retval_send(0);
1278 set_state(STATE_SLEEPING, 1, addr);
1279 next_wakeup_valid = 0;
1281 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1283 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1285 set_state(STATE_WAITING_PROBE, 1, addr);
1287 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1288 next_wakeup_valid = 1;
1290 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING) {
1292 /* The user requested a reannouncing of the address by a SIGHUP */
1293 daemon_log(LOG_INFO, "Reannouncing address.");
1295 /* Send announcement packet */
1296 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1297 set_state(STATE_ANNOUNCING, 1, addr);
1299 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1300 next_wakeup_valid = 1;
1304 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1306 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1309 avahi_free(out_packet);
1314 avahi_free(in_packet);
1321 if (next_wakeup_valid) {
1322 usec = avahi_age(&next_wakeup);
1323 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1326 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1328 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1332 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1334 } else if (r == 0) {
1335 event = EVENT_TIMEOUT;
1336 next_wakeup_valid = 0;
1340 if (pollfds[FD_ARP].revents) {
1342 if (pollfds[FD_ARP].revents == POLLERR) {
1343 /* The interface is probably down, let's recreate our socket */
1347 if ((fd = open_socket(iface, hw_address)) < 0)
1350 pollfds[FD_ARP].fd = fd;
1354 assert(pollfds[FD_ARP].revents == POLLIN);
1356 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1360 event = EVENT_PACKET;
1364 if (event == EVENT_NULL &&
1365 pollfds[FD_IFACE].revents) {
1367 assert(pollfds[FD_IFACE].revents == POLLIN);
1369 if (iface_process(&event) < 0)
1373 if (event == EVENT_NULL &&
1374 pollfds[FD_SIGNAL].revents) {
1377 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1379 if ((sig = daemon_signal_next()) <= 0) {
1380 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1387 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1392 waitpid(-1, NULL, WNOHANG);
1396 event = EVENT_REFRESH_REQUEST;
1408 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1409 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1411 avahi_free(out_packet);
1412 avahi_free(in_packet);
1420 if (daemonize && !retval_sent)
1421 daemon_retval_send(ret);
1427 avahi_free(address_fn);
1433 static void help(FILE *f, const char *a0) {
1435 "%s [options] INTERFACE\n"
1436 " -h --help Show this help\n"
1437 " -D --daemonize Daemonize after startup\n"
1438 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1439 " -k --kill Kill a running daemon\n"
1440 " -r --refresh Request a running daemon refresh its IP address\n"
1441 " -c --check Return 0 if a daemon is already running\n"
1442 " -V --version Show version\n"
1443 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1445 " -t --script=script Action script to run (defaults to\n"
1446 " "AVAHI_IPCONF_SCRIPT")\n"
1447 " -w --wait Wait until an address has been acquired before\n"
1449 " --force-bind Assign an IPv4LL address even if a routable address\n"
1450 " is already assigned\n"
1451 " --no-drop-root Don't drop privileges\n"
1453 " --no-chroot Don't chroot()\n"
1455 " --no-proc-title Don't modify process title\n"
1456 " --debug Increase verbosity\n",
1460 static int parse_command_line(int argc, char *argv[]) {
1464 OPTION_NO_PROC_TITLE = 256,
1467 OPTION_NO_DROP_ROOT,
1473 static const struct option long_options[] = {
1474 { "help", no_argument, NULL, 'h' },
1475 { "daemonize", no_argument, NULL, 'D' },
1476 { "syslog", no_argument, NULL, 's' },
1477 { "kill", no_argument, NULL, 'k' },
1478 { "refresh", no_argument, NULL, 'r' },
1479 { "check", no_argument, NULL, 'c' },
1480 { "version", no_argument, NULL, 'V' },
1481 { "start", required_argument, NULL, 'S' },
1482 { "script", required_argument, NULL, 't' },
1483 { "wait", no_argument, NULL, 'w' },
1484 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1485 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1487 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1489 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1490 { "debug", no_argument, NULL, OPTION_DEBUG },
1491 { NULL, 0, NULL, 0 }
1494 while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1501 command = DAEMON_HELP;
1507 command = DAEMON_KILL;
1510 command = DAEMON_VERSION;
1513 command = DAEMON_REFRESH;
1516 command = DAEMON_CHECK;
1520 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1521 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1526 avahi_free(action_script);
1527 action_script = avahi_strdup(optarg);
1530 wait_for_address = 1;
1533 case OPTION_NO_PROC_TITLE:
1534 modify_proc_title = 0;
1541 case OPTION_FORCE_BIND:
1545 case OPTION_NO_DROP_ROOT:
1550 case OPTION_NO_CHROOT:
1560 if (command == DAEMON_RUN ||
1561 command == DAEMON_KILL ||
1562 command == DAEMON_REFRESH ||
1563 command == DAEMON_CHECK) {
1565 if (optind >= argc) {
1566 fprintf(stderr, "Missing interface name.\n");
1570 interface_name = avahi_strdup(argv[optind++]);
1573 if (optind != argc) {
1574 fprintf(stderr, "Too many arguments\n");
1579 action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1584 static const char* pid_file_proc(void) {
1585 return pid_file_name;
1588 int main(int argc, char*argv[]) {
1590 char *log_ident = NULL;
1592 signal(SIGPIPE, SIG_IGN);
1594 if ((argv0 = strrchr(argv[0], '/')))
1595 argv0 = avahi_strdup(argv0 + 1);
1597 argv0 = avahi_strdup(argv[0]);
1599 daemon_log_ident = argv0;
1601 if (parse_command_line(argc, argv) < 0)
1604 if (modify_proc_title)
1605 avahi_init_proc_title(argc, argv);
1607 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1608 daemon_pid_file_proc = pid_file_proc;
1609 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1611 if (command == DAEMON_RUN) {
1617 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1618 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1622 if (getuid() != 0) {
1623 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1627 if ((pid = daemon_pid_file_is_running()) >= 0) {
1628 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1633 daemon_retval_init();
1635 if ((pid = daemon_fork()) < 0)
1637 else if (pid != 0) {
1641 if ((ret = daemon_retval_wait(20)) < 0) {
1642 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1653 if (use_syslog || daemonize)
1654 daemon_log_use = DAEMON_LOG_SYSLOG;
1658 if (daemon_pid_file_create() < 0) {
1659 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1662 daemon_retval_send(1);
1667 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1669 if (loop(ifindex, start_address) < 0)
1673 } else if (command == DAEMON_HELP) {
1674 help(stdout, argv0);
1677 } else if (command == DAEMON_VERSION) {
1678 printf("%s "PACKAGE_VERSION"\n", argv0);
1681 } else if (command == DAEMON_KILL) {
1682 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1683 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1688 } else if (command == DAEMON_REFRESH) {
1689 if (daemon_pid_file_kill(SIGHUP) < 0) {
1690 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1695 } else if (command == DAEMON_CHECK)
1696 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1702 daemon_retval_done();
1705 daemon_pid_file_remove();
1707 avahi_free(log_ident);
1708 avahi_free(pid_file_name);
1710 avahi_free(interface_name);
1711 avahi_free(action_script);