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>
86 /* An implementation of RFC 3927 */
88 /* Constants from the RFC */
93 #define ANNOUNCE_WAIT 2
94 #define ANNOUNCE_NUM 2
95 #define ANNOUNCE_INTERVAL 2
96 #define MAX_CONFLICTS 10
97 #define RATE_LIMIT_INTERVAL 60
98 #define DEFEND_INTERVAL 10
100 #define IPV4LL_NETWORK 0xA9FE0000L
101 #define IPV4LL_NETMASK 0xFFFF0000L
102 #define IPV4LL_HOSTMASK 0x0000FFFFL
103 #define IPV4LL_BROADCAST 0xA9FEFFFFL
105 #define ETHER_ADDRLEN 6
106 #define ETHER_HDR_SIZE (2+2*ETHER_ADDRLEN)
107 #define ARP_PACKET_SIZE (8+4+4+2*ETHER_ADDRLEN)
109 typedef enum ArpOperation {
114 typedef struct ArpPacketInfo {
115 ArpOperation operation;
117 uint32_t sender_ip_address, target_ip_address;
118 uint8_t sender_hw_address[ETHER_ADDRLEN], target_hw_address[ETHER_ADDRLEN];
121 typedef struct ArpPacket {
122 uint8_t *ether_header;
123 uint8_t *ether_payload;
126 static State state = STATE_START;
127 static int n_iteration = 0;
128 static int n_conflict = 0;
130 static char *interface_name = NULL;
131 static char *pid_file_name = NULL;
132 static uint32_t start_address = 0;
133 static char *argv0 = NULL;
134 static int daemonize = 0;
135 static int wait_for_address = 0;
136 static int use_syslog = 0;
137 static int debug = 0;
138 static int modify_proc_title = 1;
139 static int force_bind = 0;
141 static int no_chroot = 0;
143 static int no_drop_root = 0;
144 static int wrote_pid_file = 0;
145 static char *action_script = NULL;
154 } command = DAEMON_RUN;
156 typedef enum CalloutEvent {
164 static const char * const callout_event_table[CALLOUT_MAX] = {
165 [CALLOUT_BIND] = "BIND",
166 [CALLOUT_CONFLICT] = "CONFLICT",
167 [CALLOUT_UNBIND] = "UNBIND",
168 [CALLOUT_STOP] = "STOP"
171 typedef struct CalloutEventInfo {
177 #define RANDOM_DEVICE "/dev/urandom"
186 static void init_rand_seed(void) {
190 /* Try to initialize seed from /dev/urandom, to make it a little
191 * less predictable, and to make sure that multiple machines
192 * booted at the same time choose different random seeds. */
193 if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
194 read(fd, &seed, sizeof(seed));
198 /* If the initialization failed by some reason, we add the time to the seed */
199 seed ^= (unsigned) time(NULL);
204 static uint32_t pick_addr(uint32_t old_addr) {
208 unsigned r = (unsigned) rand();
210 /* Reduce to 16 bits */
212 r = (r >> 16) ^ (r & 0xFFFF);
214 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
216 } while (addr == old_addr || !is_ll_address(addr));
221 static int load_address(const char *fn, uint32_t *addr) {
228 if (!(f = fopen(fn, "r"))) {
230 if (errno == ENOENT) {
235 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
239 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
240 daemon_log(LOG_ERR, "Parse failure");
246 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
256 static int save_address(const char *fn, uint32_t addr) {
264 if (!(f = fopen(fn, "w"))) {
265 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
270 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
285 * Allocate a buffer with two pointers in front, one of which is
286 * guaranteed to point ETHER_HDR_SIZE bytes into it.
288 static ArpPacket* packet_new(size_t packet_len) {
292 assert(packet_len > 0);
295 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
297 p->ether_header = NULL;
298 p->ether_payload = b + sizeof(struct ArpPacket);
301 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
303 p->ether_header = b + sizeof(struct ArpPacket);
304 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
310 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
315 assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
316 assert(packet_len != NULL);
318 *packet_len = ARP_PACKET_SIZE;
319 p = packet_new(*packet_len);
320 r = p->ether_payload;
322 r[1] = 1; /* HTYPE */
323 r[2] = 8; /* PTYPE */
324 r[4] = ETHER_ADDRLEN; /* HLEN */
326 r[7] = (uint8_t) info->operation;
328 memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
329 memcpy(r+14, &info->sender_ip_address, 4);
330 memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
331 memcpy(r+24, &info->target_ip_address, 4);
336 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
339 memset(&info, 0, sizeof(info));
340 info.operation = ARP_REQUEST;
341 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
342 info.target_ip_address = ip_address;
344 return packet_new_with_info(&info, packet_len);
347 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
350 memset(&info, 0, sizeof(info));
351 info.operation = ARP_REQUEST;
352 memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
353 info.target_ip_address = ip_address;
354 info.sender_ip_address = ip_address;
356 return packet_new_with_info(&info, packet_len);
359 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
363 p = (uint8_t *)packet->ether_payload;
366 if (packet_len < ARP_PACKET_SIZE)
369 /* Check HTYPE and PTYPE */
370 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
373 /* Check HLEN, PLEN, OPERATION */
374 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
377 info->operation = p[7];
378 memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
379 memcpy(&info->sender_ip_address, p+14, 4);
380 memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
381 memcpy(&info->target_ip_address, p+24, 4);
386 static void set_state(State st, int reset_counter, uint32_t address) {
387 static const char* const state_table[] = {
388 [STATE_START] = "START",
389 [STATE_WAITING_PROBE] = "WAITING_PROBE",
390 [STATE_PROBING] = "PROBING",
391 [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
392 [STATE_ANNOUNCING] = "ANNOUNCING",
393 [STATE_RUNNING] = "RUNNING",
394 [STATE_SLEEPING] = "SLEEPING"
398 assert(st < STATE_MAX);
400 if (st == state && !reset_counter) {
402 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
404 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
409 if (state == STATE_SLEEPING)
410 avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
411 else if (state == STATE_ANNOUNCING)
412 avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
413 else if (state == STATE_RUNNING)
414 avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
416 avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
419 static int interface_up(int iface) {
423 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
424 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
428 memset(&ifreq, 0, sizeof(ifreq));
429 if (!if_indextoname(iface, ifreq.ifr_name)) {
430 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
434 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
435 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
439 ifreq.ifr_flags |= IFF_UP;
441 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
442 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
459 /* Linux 'packet socket' specific implementation */
461 static int open_socket(int iface, uint8_t *hw_address) {
463 struct sockaddr_ll sa;
466 if (interface_up(iface) < 0)
469 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
470 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
474 memset(&sa, 0, sizeof(sa));
475 sa.sll_family = AF_PACKET;
476 sa.sll_protocol = htons(ETH_P_ARP);
477 sa.sll_ifindex = iface;
479 if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
480 daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
485 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
486 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
490 if (sa.sll_halen != ETHER_ADDRLEN) {
491 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
495 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
506 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
507 struct sockaddr_ll sa;
511 assert(packet_len > 0);
513 memset(&sa, 0, sizeof(sa));
514 sa.sll_family = AF_PACKET;
515 sa.sll_protocol = htons(ETH_P_ARP);
516 sa.sll_ifindex = iface;
517 sa.sll_halen = ETHER_ADDRLEN;
518 memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
520 if (sendto(fd, packet->ether_payload, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
521 daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
528 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
530 struct sockaddr_ll sa;
540 if (ioctl(fd, FIONREAD, &s) < 0) {
541 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
548 *packet = packet_new(s);
551 if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
552 daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
556 *packet_len = (size_t) r;
570 close_socket(int fd) {
574 #else /* !__linux__ */
575 /* PCAP-based implementation */
578 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
579 static uint8_t __lladdr[ETHER_ADDRLEN];
582 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
586 __get_ether_addr(int ifindex, u_char *lladdr)
590 struct if_msghdr *ifm;
593 struct sockaddr_dl *sdl;
600 mib[4] = NET_RT_IFLIST;
603 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
604 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
611 daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
615 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
616 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
623 for (next = buf; next < lim; next += ifm->ifm_msglen) {
624 ifm = (struct if_msghdr *)next;
625 if (ifm->ifm_type == RTM_IFINFO) {
626 sdl = (struct sockaddr_dl *)(ifm + 1);
627 memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
635 #define PCAP_TIMEOUT 500 /* 0.5s */
638 open_socket(int iface, uint8_t *hw_address)
640 struct bpf_program bpf;
642 char ifname[IFNAMSIZ];
647 assert(__pp == NULL);
649 if (interface_up(iface) < 0) {
652 if (__get_ether_addr(iface, __lladdr) == -1) {
655 if (if_indextoname(iface, ifname) == NULL) {
660 * Using a timeout for BPF is fairly portable across BSDs. On most
661 * modern versions, using the timeout/nonblock/poll method results in
662 * fairly sane behavior, with the timeout only coming into play during
663 * the next_ex() call itself (so, for us, that's only when there's
664 * data). On older versions, it may result in a PCAP_TIMEOUT busy-wait
665 * on some versions, though, as the poll() may terminate at the
666 * PCAP_TIMEOUT instead of the poll() timeout.
668 pp = pcap_open_live(ifname, 1500, 0, PCAP_TIMEOUT, __pcap_errbuf);
672 err = pcap_set_datalink(pp, DLT_EN10MB);
674 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
678 err = pcap_setdirection(pp, PCAP_D_IN);
680 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
685 fd = pcap_get_selectable_fd(pp);
692 * Using setnonblock is a portability stop-gap. Using the timeout in
693 * combination with setnonblock will ensure on most BSDs that the
694 * next_ex call returns in a timely fashion.
696 err = pcap_setnonblock(pp, 1, __pcap_errbuf);
702 filter = avahi_strdup_printf("arp and (ether dst ff:ff:ff:ff:ff:ff or "
703 "%02x:%02x:%02x:%02x:%02x:%02x)",
704 __lladdr[0], __lladdr[1],
705 __lladdr[2], __lladdr[3],
706 __lladdr[4], __lladdr[5]);
707 DEBUG(daemon_log(LOG_DEBUG, "Using pcap filter '%s'", filter));
709 err = pcap_compile(pp, &bpf, filter, 1, 0);
712 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
716 err = pcap_setfilter(pp, &bpf);
718 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
724 /* Stash pcap-specific context away. */
725 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
732 close_socket(int fd __unused)
735 assert(__pp != NULL);
741 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
742 * and prepend the required ethernet header information before sending.
745 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
748 struct ether_header *eh;
750 assert(__pp != NULL);
751 assert(packet != NULL);
753 eh = (struct ether_header *)packet->ether_header;
754 memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
755 memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
756 eh->ether_type = htons(0x0806);
758 return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
762 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
764 struct pcap_pkthdr *ph;
770 assert(__pp != NULL);
771 assert(packet != NULL);
772 assert(packet_len != NULL);
778 err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
779 if (err == 1 && ph->caplen <= ph->len) {
780 ap = packet_new(ph->caplen);
781 memcpy(ap->ether_header, pd, ph->caplen);
783 *packet_len = (ph->caplen - sizeof(struct ether_header));
785 } else if (err >= 0) {
787 * err == 1: Just drop bogus packets (>1500 for an arp packet!?)
790 * err == 0: We might have had traffic on the pcap fd that
791 * didn't match the filter, in which case we'll get 0 packets.
795 daemon_log(LOG_ERR, "pcap_next_ex(%d): %s",
796 err, pcap_geterr(__pp));
801 #endif /* __linux__ */
803 int is_ll_address(uint32_t addr) {
805 ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
806 ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
807 ((ntohl(addr) & 0x0000FF00) != 0xFF00);
810 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
813 gettimeofday(tv, NULL);
816 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
819 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
824 static FILE* fork_dispatcher(void) {
830 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
834 if ((pid = fork()) < 0)
840 /* Please note that the signal pipe is not closed at this
841 * point, signals will thus be dispatched in the main
844 daemon_retval_done();
848 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
852 if (!(f = fdopen(fds[0], "r"))) {
853 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
854 goto dispatcher_fail;
858 CalloutEventInfo info;
859 char name[IFNAMSIZ], buf[64];
862 if (fread(&info, sizeof(info), 1, f) != 1) {
866 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
867 goto dispatcher_fail;
870 assert(info.event <= CALLOUT_MAX);
872 if (!if_indextoname(info.ifindex, name)) {
873 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
877 if (daemon_exec("/", &k,
878 action_script, action_script,
879 callout_event_table[info.event],
881 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
883 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
888 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
899 /* If the main process is trapped inside a chroot() we have to
900 * remove the PID file for it */
902 if (!no_chroot && wrote_pid_file)
903 daemon_pid_file_remove();
914 if (!(ret = fdopen(fds[1], "w"))) {
915 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
930 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
931 CalloutEventInfo info;
932 char buf[64], ifname[IFNAMSIZ];
934 daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
935 callout_event_table[event],
936 inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
937 if_indextoname(iface, ifname));
940 info.ifindex = iface;
943 if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
944 daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
951 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
953 static int drop_privs(void) {
962 /* Get user/group ID */
966 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
967 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
971 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
972 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
976 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);
979 /* Create directory */
981 r = mkdir(AVAHI_IPDATA_DIR, 0755);
984 if (r < 0 && errno != EEXIST) {
985 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
989 /* Convey working directory */
994 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
996 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
997 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
1001 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1002 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
1010 if (chroot(AVAHI_IPDATA_DIR) < 0) {
1011 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
1015 daemon_log(LOG_INFO, "Successfully called chroot().");
1018 /* Since we are now trapped inside a chroot we cannot remove
1019 * the pid file anymore, the helper process will do that for us. */
1025 if (!no_drop_root) {
1027 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1028 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1032 #if defined(HAVE_SETRESGID)
1033 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1034 #elif defined(HAVE_SETEGID)
1035 if ((r = setgid(gr->gr_gid)) >= 0)
1036 r = setegid(gr->gr_gid);
1037 #elif defined(HAVE_SETREGID)
1038 r = setregid(gr->gr_gid, gr->gr_gid);
1040 #error "No API to drop privileges"
1044 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1048 #if defined(HAVE_SETRESUID)
1049 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1050 #elif defined(HAVE_SETEUID)
1051 if ((r = setuid(pw->pw_uid)) >= 0)
1052 r = seteuid(pw->pw_uid);
1053 #elif defined(HAVE_SETREUID)
1054 r = setreuid(pw->pw_uid, pw->pw_uid);
1056 #error "No API to drop privileges"
1060 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1064 set_env("USER", pw->pw_name);
1065 set_env("LOGNAME", pw->pw_name);
1066 set_env("HOME", pw->pw_dir);
1068 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1074 static int loop(int iface, uint32_t addr) {
1082 int fd = -1, ret = -1;
1083 struct timeval next_wakeup;
1084 int next_wakeup_valid = 0;
1086 ArpPacket *in_packet = NULL;
1087 size_t in_packet_len;
1088 ArpPacket *out_packet = NULL;
1089 size_t out_packet_len;
1090 uint8_t hw_address[ETHER_ADDRLEN];
1091 struct pollfd pollfds[FD_MAX];
1093 Event event = EVENT_NULL;
1094 int retval_sent = !daemonize;
1096 FILE *dispatcher = NULL;
1097 char *address_fn = NULL;
1100 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1102 if (!(dispatcher = fork_dispatcher()))
1105 if ((fd = open_socket(iface, hw_address)) < 0)
1108 if ((iface_fd = iface_init(iface)) < 0)
1111 if (drop_privs() < 0)
1116 else if (iface_get_initial_state(&st) < 0)
1124 p = AVAHI_IPDATA_DIR;
1126 address_fn = avahi_strdup_printf(
1127 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1128 hw_address[0], hw_address[1],
1129 hw_address[2], hw_address[3],
1130 hw_address[4], hw_address[5]);
1133 load_address(address_fn, &addr);
1135 if (addr && !is_ll_address(addr)) {
1136 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)));
1144 for (i = 0; i < ETHER_ADDRLEN; i++)
1145 a += hw_address[i]*i;
1147 a = (a % 0xFE00) + 0x0100;
1149 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1152 assert(is_ll_address(addr));
1154 set_state(st, 1, addr);
1156 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1158 if (state == STATE_SLEEPING)
1159 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1161 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1162 daemon_retval_send(0);
1166 memset(pollfds, 0, sizeof(pollfds));
1167 pollfds[FD_ARP].fd = fd;
1168 pollfds[FD_ARP].events = POLLIN;
1169 pollfds[FD_IFACE].fd = iface_fd;
1170 pollfds[FD_IFACE].events = POLLIN;
1171 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1172 pollfds[FD_SIGNAL].events = POLLIN;
1178 if (state == STATE_START) {
1180 /* First, wait a random time */
1181 set_state(STATE_WAITING_PROBE, 1, addr);
1183 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1184 next_wakeup_valid = 1;
1186 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1187 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1190 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1191 set_state(STATE_PROBING, 0, addr);
1193 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1194 next_wakeup_valid = 1;
1196 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1198 /* Send the last probe */
1199 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1200 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1202 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1203 next_wakeup_valid = 1;
1205 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1206 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1208 /* Send announcement packet */
1209 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1210 set_state(STATE_ANNOUNCING, 0, addr);
1212 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1213 next_wakeup_valid = 1;
1215 if (n_iteration == 0) {
1216 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1222 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1224 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1225 set_state(STATE_RUNNING, 0, addr);
1227 next_wakeup_valid = 0;
1229 save_address(address_fn, addr);
1232 daemon_retval_send(0);
1236 } else if (event == EVENT_PACKET) {
1241 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1242 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1246 if (info.sender_ip_address == addr) {
1247 /* Normal conflict */
1249 daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1250 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1251 /* Probe conflict */
1252 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1255 daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1260 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1261 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1264 /* Pick a new address */
1265 addr = pick_addr(addr);
1267 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1271 set_state(STATE_WAITING_PROBE, 1, addr);
1273 if (n_conflict >= MAX_CONFLICTS) {
1274 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1275 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1277 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1279 next_wakeup_valid = 1;
1281 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1284 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED && !force_bind) {
1286 daemon_log(LOG_INFO, "A routable address has been configured.");
1288 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1289 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1293 daemon_retval_send(0);
1297 set_state(STATE_SLEEPING, 1, addr);
1298 next_wakeup_valid = 0;
1300 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1302 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1304 set_state(STATE_WAITING_PROBE, 1, addr);
1306 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1307 next_wakeup_valid = 1;
1309 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING) {
1311 /* The user requested a reannouncing of the address by a SIGHUP */
1312 daemon_log(LOG_INFO, "Reannouncing address.");
1314 /* Send announcement packet */
1315 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1316 set_state(STATE_ANNOUNCING, 1, addr);
1318 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1319 next_wakeup_valid = 1;
1323 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1325 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1328 avahi_free(out_packet);
1333 avahi_free(in_packet);
1340 if (next_wakeup_valid) {
1341 usec = avahi_age(&next_wakeup);
1342 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1345 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1347 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1351 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1353 } else if (r == 0) {
1354 event = EVENT_TIMEOUT;
1355 next_wakeup_valid = 0;
1359 if (pollfds[FD_ARP].revents) {
1361 if (pollfds[FD_ARP].revents == POLLERR) {
1362 /* The interface is probably down, let's recreate our socket */
1366 if ((fd = open_socket(iface, hw_address)) < 0)
1369 pollfds[FD_ARP].fd = fd;
1373 assert(pollfds[FD_ARP].revents == POLLIN);
1375 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1379 event = EVENT_PACKET;
1383 if (event == EVENT_NULL &&
1384 pollfds[FD_IFACE].revents) {
1386 assert(pollfds[FD_IFACE].revents == POLLIN);
1388 if (iface_process(&event) < 0)
1392 if (event == EVENT_NULL &&
1393 pollfds[FD_SIGNAL].revents) {
1396 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1398 if ((sig = daemon_signal_next()) <= 0) {
1399 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1406 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1411 waitpid(-1, NULL, WNOHANG);
1415 event = EVENT_REFRESH_REQUEST;
1427 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1428 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1430 avahi_free(out_packet);
1431 avahi_free(in_packet);
1439 if (daemonize && !retval_sent)
1440 daemon_retval_send(ret);
1446 avahi_free(address_fn);
1452 static void help(FILE *f, const char *a0) {
1454 "%s [options] INTERFACE\n"
1455 " -h --help Show this help\n"
1456 " -D --daemonize Daemonize after startup\n"
1457 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1458 " -k --kill Kill a running daemon\n"
1459 " -r --refresh Request a running daemon refresh its IP address\n"
1460 " -c --check Return 0 if a daemon is already running\n"
1461 " -V --version Show version\n"
1462 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1464 " -t --script=script Action script to run (defaults to\n"
1465 " "AVAHI_IPCONF_SCRIPT")\n"
1466 " -w --wait Wait until an address has been acquired before\n"
1468 " --force-bind Assign an IPv4LL address even if a routable address\n"
1469 " is already assigned\n"
1470 " --no-drop-root Don't drop privileges\n"
1472 " --no-chroot Don't chroot()\n"
1474 " --no-proc-title Don't modify process title\n"
1475 " --debug Increase verbosity\n",
1479 static int parse_command_line(int argc, char *argv[]) {
1483 OPTION_NO_PROC_TITLE = 256,
1486 OPTION_NO_DROP_ROOT,
1492 static const struct option long_options[] = {
1493 { "help", no_argument, NULL, 'h' },
1494 { "daemonize", no_argument, NULL, 'D' },
1495 { "syslog", no_argument, NULL, 's' },
1496 { "kill", no_argument, NULL, 'k' },
1497 { "refresh", no_argument, NULL, 'r' },
1498 { "check", no_argument, NULL, 'c' },
1499 { "version", no_argument, NULL, 'V' },
1500 { "start", required_argument, NULL, 'S' },
1501 { "script", required_argument, NULL, 't' },
1502 { "wait", no_argument, NULL, 'w' },
1503 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1504 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1506 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1508 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1509 { "debug", no_argument, NULL, OPTION_DEBUG },
1510 { NULL, 0, NULL, 0 }
1513 while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1520 command = DAEMON_HELP;
1526 command = DAEMON_KILL;
1529 command = DAEMON_VERSION;
1532 command = DAEMON_REFRESH;
1535 command = DAEMON_CHECK;
1539 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1540 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1545 avahi_free(action_script);
1546 action_script = avahi_strdup(optarg);
1549 wait_for_address = 1;
1552 case OPTION_NO_PROC_TITLE:
1553 modify_proc_title = 0;
1560 case OPTION_FORCE_BIND:
1564 case OPTION_NO_DROP_ROOT:
1569 case OPTION_NO_CHROOT:
1579 if (command == DAEMON_RUN ||
1580 command == DAEMON_KILL ||
1581 command == DAEMON_REFRESH ||
1582 command == DAEMON_CHECK) {
1584 if (optind >= argc) {
1585 fprintf(stderr, "Missing interface name.\n");
1589 interface_name = avahi_strdup(argv[optind++]);
1592 if (optind != argc) {
1593 fprintf(stderr, "Too many arguments\n");
1598 action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1603 static const char* pid_file_proc(void) {
1604 return pid_file_name;
1607 int main(int argc, char*argv[]) {
1609 char *log_ident = NULL;
1611 signal(SIGPIPE, SIG_IGN);
1613 if ((argv0 = strrchr(argv[0], '/')))
1614 argv0 = avahi_strdup(argv0 + 1);
1616 argv0 = avahi_strdup(argv[0]);
1618 daemon_log_ident = argv0;
1620 if (parse_command_line(argc, argv) < 0)
1623 if (modify_proc_title)
1624 avahi_init_proc_title(argc, argv);
1626 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1627 daemon_pid_file_proc = pid_file_proc;
1628 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1630 if (command == DAEMON_RUN) {
1636 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1637 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1641 if (getuid() != 0) {
1642 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1646 if ((pid = daemon_pid_file_is_running()) >= 0) {
1647 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1652 daemon_retval_init();
1654 if ((pid = daemon_fork()) < 0)
1656 else if (pid != 0) {
1660 if ((ret = daemon_retval_wait(20)) < 0) {
1661 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1672 if (use_syslog || daemonize)
1673 daemon_log_use = DAEMON_LOG_SYSLOG;
1677 if (daemon_pid_file_create() < 0) {
1678 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1681 daemon_retval_send(1);
1686 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1688 if (loop(ifindex, start_address) < 0)
1692 } else if (command == DAEMON_HELP) {
1693 help(stdout, argv0);
1696 } else if (command == DAEMON_VERSION) {
1697 printf("%s "PACKAGE_VERSION"\n", argv0);
1700 } else if (command == DAEMON_KILL) {
1701 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1702 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1707 } else if (command == DAEMON_REFRESH) {
1708 if (daemon_pid_file_kill(SIGHUP) < 0) {
1709 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1714 } else if (command == DAEMON_CHECK)
1715 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1721 daemon_retval_done();
1724 daemon_pid_file_remove();
1726 avahi_free(log_ident);
1727 avahi_free(pid_file_name);
1729 avahi_free(interface_name);
1730 avahi_free(action_script);