Lines Matching defs:*
0 /* $Id$ */
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
19 USA.
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
26 #include <sys/param.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/ioctl.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 #ifdef __FreeBSD__
33 #include <sys/sysctl.h>
34 #endif
36 #ifdef __linux__
37 #include <netpacket/packet.h>
38 #endif
39 #include <net/ethernet.h>
40 #include <net/if.h>
41 #ifdef __FreeBSD__
42 #include <net/if_dl.h>
43 #include <net/route.h>
44 #endif
45 #include <arpa/inet.h>
47 #include <assert.h>
48 #include <errno.h>
49 #include <inttypes.h>
50 #include <fcntl.h>
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <signal.h>
54 #include <string.h>
55 #include <time.h>
56 #include <getopt.h>
58 #include <grp.h>
59 #include <poll.h>
60 #include <pwd.h>
61 #include <unistd.h>
63 #ifndef __linux__
64 #include <pcap.h>
66 /* Old versions of PCAP defined it as D_IN */
67 #ifndef PCAP_D_IN
68 #define PCAP_D_IN D_IN
69 #endif
71 #endif
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>
83 #include "main.h"
84 #include "iface.h"
86 /* An implementation of RFC 3927 */
88 /* Constants from the RFC */
89 #define PROBE_WAIT 1
90 #define PROBE_NUM 3
91 #define PROBE_MIN 1
92 #define PROBE_MAX 2
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 {
110 ARP_REQUEST = 1,
111 ARP_RESPONSE = 2
112 } 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];
119 } ArpPacketInfo;
121 typedef struct ArpPacket {
122 uint8_t *ether_header;
123 uint8_t *ether_payload;
124 } ArpPacket;
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;
140 #ifdef HAVE_CHROOT
141 static int no_chroot = 0;
142 #endif
143 static int no_drop_root = 0;
144 static int wrote_pid_file = 0;
145 static char *action_script = NULL;
147 static enum {
148 DAEMON_RUN,
149 DAEMON_KILL,
150 DAEMON_REFRESH,
151 DAEMON_VERSION,
152 DAEMON_HELP,
153 DAEMON_CHECK
154 } command = DAEMON_RUN;
156 typedef enum CalloutEvent {
157 CALLOUT_BIND,
158 CALLOUT_CONFLICT,
159 CALLOUT_UNBIND,
160 CALLOUT_STOP,
161 CALLOUT_MAX
162 } 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 {
172 CalloutEvent event;
173 uint32_t address;
174 int ifindex;
175 } CalloutEventInfo;
177 #define RANDOM_DEVICE "/dev/urandom"
179 #define DEBUG(x) \
180 do { \
181 if (debug) { \
182 x; \
184 } while (0)
186 static void init_rand_seed(void) {
187 int fd;
188 unsigned seed = 0;
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));
195 close(fd);
198 /* If the initialization failed by some reason, we add the time to the seed */
199 seed ^= (unsigned) time(NULL);
201 srand(seed);
204 static uint32_t pick_addr(uint32_t old_addr) {
205 uint32_t addr;
207 do {
208 unsigned r = (unsigned) rand();
210 /* Reduce to 16 bits */
211 while (r > 0xFFFF)
212 r = (r >> 16) ^ (r & 0xFFFF);
214 addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
216 } while (addr == old_addr || !is_ll_address(addr));
218 return addr;
221 static int load_address(const char *fn, uint32_t *addr) {
222 FILE *f;
223 unsigned a, b, c, d;
225 assert(fn);
226 assert(addr);
228 if (!(f = fopen(fn, "r"))) {
230 if (errno == ENOENT) {
231 *addr = 0;
232 return 0;
235 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
236 goto fail;
239 if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
240 daemon_log(LOG_ERR, "Parse failure");
241 goto fail;
244 fclose(f);
246 *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
247 return 0;
249 fail:
250 if (f)
251 fclose(f);
253 return -1;
256 static int save_address(const char *fn, uint32_t addr) {
257 FILE *f;
258 char buf[32];
259 mode_t u;
261 assert(fn);
263 u = umask(0033);
264 if (!(f = fopen(fn, "w"))) {
265 daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
266 goto fail;
268 umask(u);
270 fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
271 fclose(f);
273 return 0;
275 fail:
276 if (f)
277 fclose(f);
279 umask(u);
281 return -1;
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) {
289 ArpPacket *p;
290 uint8_t *b;
292 assert(packet_len > 0);
294 #ifdef __linux__
295 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
296 p = (ArpPacket*) b;
297 p->ether_header = NULL;
298 p->ether_payload = b + sizeof(struct ArpPacket);
300 #else
301 b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
302 p = (ArpPacket*) b;
303 p->ether_header = b + sizeof(struct ArpPacket);
304 p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
305 #endif
307 return p;
310 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
311 ArpPacket *p = NULL;
312 uint8_t *r;
314 assert(info);
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 */
325 r[5] = 4; /* PLEN */
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);
333 return p;
336 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
337 ArpPacketInfo info;
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) {
348 ArpPacketInfo info;
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) {
360 const uint8_t *p;
362 assert(packet);
363 p = (uint8_t *)packet->ether_payload;
364 assert(p);
366 if (packet_len < ARP_PACKET_SIZE)
367 return -1;
369 /* Check HTYPE and PTYPE */
370 if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
371 return -1;
373 /* Check HLEN, PLEN, OPERATION */
374 if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
375 return -1;
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);
383 return 0;
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"
396 char buf[64];
398 assert(st < STATE_MAX);
400 if (st == state && !reset_counter) {
401 n_iteration++;
402 DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
403 } else {
404 DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
405 state = st;
406 n_iteration = 0;
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)));
415 else
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) {
420 int fd = -1;
421 struct ifreq ifreq;
423 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
424 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
425 goto fail;
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));
431 goto fail;
434 if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
435 daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
436 goto fail;
439 ifreq.ifr_flags |= IFF_UP;
441 if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
442 daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
443 goto fail;
446 close(fd);
448 return 0;
450 fail:
451 if (fd >= 0)
452 close(fd);
454 return -1;
457 #ifdef __linux__
459 /* Linux 'packet socket' specific implementation */
461 static int open_socket(int iface, uint8_t *hw_address) {
462 int fd = -1;
463 struct sockaddr_ll sa;
464 socklen_t sa_len;
466 if (interface_up(iface) < 0)
467 goto fail;
469 if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
470 daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
471 goto fail;
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));
481 goto fail;
484 sa_len = sizeof(sa);
485 if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
486 daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
487 goto fail;
490 if (sa.sll_halen != ETHER_ADDRLEN) {
491 daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
492 goto fail;
495 memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
497 return fd;
499 fail:
500 if (fd >= 0)
501 close(fd);
503 return -1;
506 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
507 struct sockaddr_ll sa;
509 assert(fd >= 0);
510 assert(packet);
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));
522 return -1;
525 return 0;
528 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
529 int s;
530 struct sockaddr_ll sa;
531 socklen_t sa_len;
532 ssize_t r;
534 assert(fd >= 0);
535 assert(packet);
536 assert(packet_len);
538 *packet = NULL;
540 if (ioctl(fd, FIONREAD, &s) < 0) {
541 daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
542 goto fail;
545 if (s <= 0)
546 s = 4096;
548 *packet = packet_new(s);
550 sa_len = sizeof(sa);
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));
553 goto fail;
556 *packet_len = (size_t) r;
558 return 0;
560 fail:
561 if (*packet) {
562 avahi_free(*packet);
563 *packet = NULL;
566 return -1;
569 static void
570 close_socket(int fd) {
571 close(fd);
574 #else /* !__linux__ */
575 /* PCAP-based implementation */
577 static pcap_t *__pp;
578 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
579 static uint8_t __lladdr[ETHER_ADDRLEN];
581 #ifndef elementsof
582 #define elementsof(array) (sizeof(array)/sizeof(array[0]))
583 #endif
585 static int
586 __get_ether_addr(int ifindex, u_char *lladdr)
588 int mib[6];
589 char *buf;
590 struct if_msghdr *ifm;
591 char *lim;
592 char *next;
593 struct sockaddr_dl *sdl;
594 size_t len;
596 mib[0] = CTL_NET;
597 mib[1] = PF_ROUTE;
598 mib[2] = 0;
599 mib[3] = 0;
600 mib[4] = NET_RT_IFLIST;
601 mib[5] = ifindex;
603 if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
604 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
605 strerror(errno));
606 return (-1);
609 buf = malloc(len);
610 if (buf == NULL) {
611 daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
612 return (-1);
615 if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
616 daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
617 strerror(errno));
618 free(buf);
619 return (-1);
622 lim = buf + len;
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);
630 free(buf);
632 return (0);
635 #define PCAP_TIMEOUT 500 /* 0.5s */
637 static int
638 open_socket(int iface, uint8_t *hw_address)
640 struct bpf_program bpf;
641 char *filter;
642 char ifname[IFNAMSIZ];
643 pcap_t *pp;
644 int err;
645 int fd;
647 assert(__pp == NULL);
649 if (interface_up(iface) < 0) {
650 return (-1);
652 if (__get_ether_addr(iface, __lladdr) == -1) {
653 return (-1);
655 if (if_indextoname(iface, ifname) == NULL) {
656 return (-1);
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);
669 if (pp == NULL) {
670 return (-1);
672 err = pcap_set_datalink(pp, DLT_EN10MB);
673 if (err == -1) {
674 daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
675 pcap_close(pp);
676 return (-1);
678 err = pcap_setdirection(pp, PCAP_D_IN);
679 if (err == -1) {
680 daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
681 pcap_close(pp);
682 return (-1);
685 fd = pcap_get_selectable_fd(pp);
686 if (fd == -1) {
687 pcap_close(pp);
688 return (-1);
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);
697 if (err == -1) {
698 pcap_close(pp);
699 return (-1);
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);
710 avahi_free(filter);
711 if (err == -1) {
712 daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
713 pcap_close(pp);
714 return (-1);
716 err = pcap_setfilter(pp, &bpf);
717 if (err == -1) {
718 daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
719 pcap_close(pp);
720 return (-1);
722 pcap_freecode(&bpf);
724 /* Stash pcap-specific context away. */
725 memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
726 __pp = pp;
728 return (fd);
731 static void
732 close_socket(int fd __unused)
735 assert(__pp != NULL);
736 pcap_close(__pp);
737 __pp = NULL;
741 * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
742 * and prepend the required ethernet header information before sending.
744 static int
745 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
746 size_t packet_len)
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)));
761 static int
762 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
764 struct pcap_pkthdr *ph;
765 u_char *pd;
766 ArpPacket *ap;
767 int err;
768 int retval;
770 assert(__pp != NULL);
771 assert(packet != NULL);
772 assert(packet_len != NULL);
774 *packet = NULL;
775 *packet_len = 0;
776 retval = -1;
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);
782 *packet = ap;
783 *packet_len = (ph->caplen - sizeof(struct ether_header));
784 retval = 0;
785 } else if (err >= 0) {
787 * err == 1: Just drop bogus packets (>1500 for an arp packet!?)
788 * on the floor.
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.
793 retval = 0;
794 } else {
795 daemon_log(LOG_ERR, "pcap_next_ex(%d): %s",
796 err, pcap_geterr(__pp));
799 return (retval);
801 #endif /* __linux__ */
803 int is_ll_address(uint32_t addr) {
804 return
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) {
811 assert(tv);
813 gettimeofday(tv, NULL);
815 if (msec)
816 avahi_timeval_add(tv, (AvahiUsec) msec*1000);
818 if (jitter)
819 avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
821 return tv;
824 static FILE* fork_dispatcher(void) {
825 FILE *ret;
826 int fds[2];
827 pid_t pid;
829 if (pipe(fds) < 0) {
830 daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
831 goto fail;
834 if ((pid = fork()) < 0)
835 goto fail;
836 else if (pid == 0) {
837 FILE *f = NULL;
838 int r = 1;
840 /* Please note that the signal pipe is not closed at this
841 * point, signals will thus be dispatched in the main
842 * process. */
844 daemon_retval_done();
846 setsid();
848 avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
850 close(fds[1]);
852 if (!(f = fdopen(fds[0], "r"))) {
853 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
854 goto dispatcher_fail;
857 for (;;) {
858 CalloutEventInfo info;
859 char name[IFNAMSIZ], buf[64];
860 int k;
862 if (fread(&info, sizeof(info), 1, f) != 1) {
863 if (feof(f))
864 break;
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));
874 continue;
877 if (daemon_exec("/", &k,
878 action_script, action_script,
879 callout_event_table[info.event],
880 name,
881 inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
883 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
884 continue;
887 if (k != 0)
888 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
891 r = 0;
893 dispatcher_fail:
895 if (f)
896 fclose(f);
898 #ifdef HAVE_CHROOT
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();
904 #endif
906 _exit(r);
909 /* parent */
911 close(fds[0]);
912 fds[0] = -1;
914 if (!(ret = fdopen(fds[1], "w"))) {
915 daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
916 goto fail;
919 return ret;
921 fail:
922 if (fds[0] >= 0)
923 close(fds[0]);
924 if (fds[1] >= 0)
925 close(fds[1]);
927 return NULL;
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));
939 info.event = event;
940 info.ifindex = iface;
941 info.address = addr;
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));
945 return -1;
948 return 0;
951 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
953 static int drop_privs(void) {
954 struct passwd *pw;
955 struct group * gr;
956 int r;
957 mode_t u;
959 pw = NULL;
960 gr = NULL;
962 /* Get user/group ID */
963 #if 0
964 if (!no_drop_root) {
966 if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
967 daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
968 return -1;
971 if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
972 daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
973 return -1;
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 #endif
980 /* Create directory */
981 u = umask(0000);
982 r = mkdir(AVAHI_IPDATA_DIR, 0755);
983 umask(u);
985 if (r < 0 && errno != EEXIST) {
986 daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
987 return -1;
990 /* Convey working directory */
992 if (!no_drop_root) {
993 struct stat st;
995 chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
997 if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
998 daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
999 return -1;
1002 if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1003 daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
1004 return -1;
1008 #ifdef HAVE_CHROOT
1010 if (!no_chroot) {
1011 if (chroot(AVAHI_IPDATA_DIR) < 0) {
1012 daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
1013 return -1;
1016 daemon_log(LOG_INFO, "Successfully called chroot().");
1017 chdir("/");
1019 /* Since we are now trapped inside a chroot we cannot remove
1020 * the pid file anymore, the helper process will do that for us. */
1021 wrote_pid_file = 0;
1024 #endif
1026 if (!no_drop_root) {
1028 if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1029 daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1030 return -1;
1033 #if defined(HAVE_SETRESGID)
1034 r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1035 #elif defined(HAVE_SETEGID)
1036 if ((r = setgid(gr->gr_gid)) >= 0)
1037 r = setegid(gr->gr_gid);
1038 #elif defined(HAVE_SETREGID)
1039 r = setregid(gr->gr_gid, gr->gr_gid);
1040 #else
1041 #error "No API to drop privileges"
1042 #endif
1044 if (r < 0) {
1045 daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1046 return -1;
1049 #if defined(HAVE_SETRESUID)
1050 r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1051 #elif defined(HAVE_SETEUID)
1052 if ((r = setuid(pw->pw_uid)) >= 0)
1053 r = seteuid(pw->pw_uid);
1054 #elif defined(HAVE_SETREUID)
1055 r = setreuid(pw->pw_uid, pw->pw_uid);
1056 #else
1057 #error "No API to drop privileges"
1058 #endif
1060 if (r < 0) {
1061 daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1062 return -1;
1065 set_env("USER", pw->pw_name);
1066 set_env("LOGNAME", pw->pw_name);
1067 set_env("HOME", pw->pw_dir);
1069 daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1072 return 0;
1075 static int loop(int iface, uint32_t addr) {
1076 enum {
1077 FD_ARP,
1078 FD_IFACE,
1079 FD_SIGNAL,
1080 FD_MAX
1083 int fd = -1, ret = -1;
1084 struct timeval next_wakeup;
1085 int next_wakeup_valid = 0;
1086 char buf[64];
1087 ArpPacket *in_packet = NULL;
1088 size_t in_packet_len;
1089 ArpPacket *out_packet = NULL;
1090 size_t out_packet_len;
1091 uint8_t hw_address[ETHER_ADDRLEN];
1092 struct pollfd pollfds[FD_MAX];
1093 int iface_fd = -1;
1094 Event event = EVENT_NULL;
1095 int retval_sent = !daemonize;
1096 State st;
1097 FILE *dispatcher = NULL;
1098 char *address_fn = NULL;
1099 const char *p;
1101 daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1103 if (!(dispatcher = fork_dispatcher()))
1104 goto fail;
1106 if ((fd = open_socket(iface, hw_address)) < 0)
1107 goto fail;
1109 if ((iface_fd = iface_init(iface)) < 0)
1110 goto fail;
1112 if (drop_privs() < 0)
1113 goto fail;
1115 if (force_bind)
1116 st = STATE_START;
1117 else if (iface_get_initial_state(&st) < 0)
1118 goto fail;
1120 #ifdef HAVE_CHROOT
1121 if (!no_chroot)
1122 p = "";
1123 else
1124 #endif
1125 p = AVAHI_IPDATA_DIR;
1127 address_fn = avahi_strdup_printf(
1128 "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1129 hw_address[0], hw_address[1],
1130 hw_address[2], hw_address[3],
1131 hw_address[4], hw_address[5]);
1133 if (!addr)
1134 load_address(address_fn, &addr);
1136 if (addr && !is_ll_address(addr)) {
1137 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)));
1138 addr = 0;
1141 if (!addr) {
1142 int i;
1143 uint32_t a = 1;
1145 for (i = 0; i < ETHER_ADDRLEN; i++)
1146 a += hw_address[i]*i;
1148 a = (a % 0xFE00) + 0x0100;
1150 addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1153 assert(is_ll_address(addr));
1155 set_state(st, 1, addr);
1157 daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1159 if (state == STATE_SLEEPING)
1160 daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1162 if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1163 daemon_retval_send(0);
1164 retval_sent = 1;
1167 memset(pollfds, 0, sizeof(pollfds));
1168 pollfds[FD_ARP].fd = fd;
1169 pollfds[FD_ARP].events = POLLIN;
1170 pollfds[FD_IFACE].fd = iface_fd;
1171 pollfds[FD_IFACE].events = POLLIN;
1172 pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1173 pollfds[FD_SIGNAL].events = POLLIN;
1175 for (;;) {
1176 int r, timeout;
1177 AvahiUsec usec;
1179 if (state == STATE_START) {
1181 /* First, wait a random time */
1182 set_state(STATE_WAITING_PROBE, 1, addr);
1184 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1185 next_wakeup_valid = 1;
1187 } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1188 (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1190 /* Send a probe */
1191 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1192 set_state(STATE_PROBING, 0, addr);
1194 elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1195 next_wakeup_valid = 1;
1197 } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1199 /* Send the last probe */
1200 out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1201 set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1203 elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1204 next_wakeup_valid = 1;
1206 } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1207 (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1209 /* Send announcement packet */
1210 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1211 set_state(STATE_ANNOUNCING, 0, addr);
1213 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1214 next_wakeup_valid = 1;
1216 if (n_iteration == 0) {
1217 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1218 goto fail;
1220 n_conflict = 0;
1223 } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1225 daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1226 set_state(STATE_RUNNING, 0, addr);
1228 next_wakeup_valid = 0;
1230 save_address(address_fn, addr);
1232 if (!retval_sent) {
1233 daemon_retval_send(0);
1234 retval_sent = 1;
1237 } else if (event == EVENT_PACKET) {
1238 ArpPacketInfo info;
1240 assert(in_packet);
1242 if (packet_parse(in_packet, in_packet_len, &info) < 0)
1243 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1244 else {
1245 int conflict = 0;
1247 if (info.sender_ip_address == addr) {
1248 /* Normal conflict */
1249 conflict = 1;
1250 daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1251 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1252 /* Probe conflict */
1253 conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1255 if (conflict)
1256 daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1259 if (conflict) {
1261 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1262 if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1263 goto fail;
1265 /* Pick a new address */
1266 addr = pick_addr(addr);
1268 daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1270 n_conflict++;
1272 set_state(STATE_WAITING_PROBE, 1, addr);
1274 if (n_conflict >= MAX_CONFLICTS) {
1275 daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1276 elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1277 } else
1278 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1280 next_wakeup_valid = 1;
1281 } else
1282 DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1285 } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED && !force_bind) {
1287 daemon_log(LOG_INFO, "A routable address has been configured.");
1289 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1290 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1291 goto fail;
1293 if (!retval_sent) {
1294 daemon_retval_send(0);
1295 retval_sent = 1;
1298 set_state(STATE_SLEEPING, 1, addr);
1299 next_wakeup_valid = 0;
1301 } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1303 daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1305 set_state(STATE_WAITING_PROBE, 1, addr);
1307 elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1308 next_wakeup_valid = 1;
1310 } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING) {
1312 /* The user requested a reannouncing of the address by a SIGHUP */
1313 daemon_log(LOG_INFO, "Reannouncing address.");
1315 /* Send announcement packet */
1316 out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1317 set_state(STATE_ANNOUNCING, 1, addr);
1319 elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1320 next_wakeup_valid = 1;
1323 if (out_packet) {
1324 DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1326 if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1327 goto fail;
1329 avahi_free(out_packet);
1330 out_packet = NULL;
1333 if (in_packet) {
1334 avahi_free(in_packet);
1335 in_packet = NULL;
1338 event = EVENT_NULL;
1339 timeout = -1;
1341 if (next_wakeup_valid) {
1342 usec = avahi_age(&next_wakeup);
1343 timeout = usec < 0 ? (int) (-usec/1000) : 0;
1346 DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1348 while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1351 if (r < 0) {
1352 daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1353 goto fail;
1354 } else if (r == 0) {
1355 event = EVENT_TIMEOUT;
1356 next_wakeup_valid = 0;
1357 } else {
1360 if (pollfds[FD_ARP].revents) {
1362 if (pollfds[FD_ARP].revents == POLLERR) {
1363 /* The interface is probably down, let's recreate our socket */
1365 close_socket(fd);
1367 if ((fd = open_socket(iface, hw_address)) < 0)
1368 goto fail;
1370 pollfds[FD_ARP].fd = fd;
1372 } else {
1374 assert(pollfds[FD_ARP].revents == POLLIN);
1376 if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1377 goto fail;
1379 if (in_packet)
1380 event = EVENT_PACKET;
1384 if (event == EVENT_NULL &&
1385 pollfds[FD_IFACE].revents) {
1387 assert(pollfds[FD_IFACE].revents == POLLIN);
1389 if (iface_process(&event) < 0)
1390 goto fail;
1393 if (event == EVENT_NULL &&
1394 pollfds[FD_SIGNAL].revents) {
1396 int sig;
1397 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1399 if ((sig = daemon_signal_next()) <= 0) {
1400 daemon_log(LOG_ERR, "daemon_signal_next() failed");
1401 goto fail;
1404 switch(sig) {
1405 case SIGINT:
1406 case SIGTERM:
1407 daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1408 ret = 0;
1409 goto fail;
1411 case SIGCHLD:
1412 waitpid(-1, NULL, WNOHANG);
1413 break;
1415 case SIGHUP:
1416 event = EVENT_REFRESH_REQUEST;
1417 break;
1424 ret = 0;
1426 fail:
1428 if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1429 do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1431 avahi_free(out_packet);
1432 avahi_free(in_packet);
1434 if (fd >= 0)
1435 close_socket(fd);
1437 if (iface_fd >= 0)
1438 iface_done();
1440 if (daemonize && !retval_sent)
1441 daemon_retval_send(ret);
1443 if (dispatcher)
1444 fclose(dispatcher);
1446 if (address_fn)
1447 avahi_free(address_fn);
1449 return ret;
1453 static void help(FILE *f, const char *a0) {
1454 fprintf(f,
1455 "%s [options] INTERFACE\n"
1456 " -h --help Show this help\n"
1457 " -D --daemonize Daemonize after startup\n"
1458 " -s --syslog Write log messages to syslog(3) instead of STDERR\n"
1459 " -k --kill Kill a running daemon\n"
1460 " -r --refresh Request a running daemon refresh its IP address\n"
1461 " -c --check Return 0 if a daemon is already running\n"
1462 " -V --version Show version\n"
1463 " -S --start=ADDRESS Start with this address from the IPv4LL range\n"
1464 " 169.254.0.0/16\n"
1465 " -t --script=script Action script to run (defaults to\n"
1466 " "AVAHI_IPCONF_SCRIPT")\n"
1467 " -w --wait Wait until an address has been acquired before\n"
1468 " daemonizing\n"
1469 " --force-bind Assign an IPv4LL address even if a routable address\n"
1470 " is already assigned\n"
1471 " --no-drop-root Don't drop privileges\n"
1472 #ifdef HAVE_CHROOT
1473 " --no-chroot Don't chroot()\n"
1474 #endif
1475 " --no-proc-title Don't modify process title\n"
1476 " --debug Increase verbosity\n",
1477 a0);
1480 static int parse_command_line(int argc, char *argv[]) {
1481 int c;
1483 enum {
1484 OPTION_NO_PROC_TITLE = 256,
1485 OPTION_FORCE_BIND,
1486 OPTION_DEBUG,
1487 OPTION_NO_DROP_ROOT,
1488 #ifdef HAVE_CHROOT
1489 OPTION_NO_CHROOT
1490 #endif
1493 static const struct option long_options[] = {
1494 { "help", no_argument, NULL, 'h' },
1495 { "daemonize", no_argument, NULL, 'D' },
1496 { "syslog", no_argument, NULL, 's' },
1497 { "kill", no_argument, NULL, 'k' },
1498 { "refresh", no_argument, NULL, 'r' },
1499 { "check", no_argument, NULL, 'c' },
1500 { "version", no_argument, NULL, 'V' },
1501 { "start", required_argument, NULL, 'S' },
1502 { "script", required_argument, NULL, 't' },
1503 { "wait", no_argument, NULL, 'w' },
1504 { "force-bind", no_argument, NULL, OPTION_FORCE_BIND },
1505 { "no-drop-root", no_argument, NULL, OPTION_NO_DROP_ROOT },
1506 #ifdef HAVE_CHROOT
1507 { "no-chroot", no_argument, NULL, OPTION_NO_CHROOT },
1508 #endif
1509 { "no-proc-title", no_argument, NULL, OPTION_NO_PROC_TITLE },
1510 { "debug", no_argument, NULL, OPTION_DEBUG },
1511 { NULL, 0, NULL, 0 }
1514 while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1516 switch(c) {
1517 case 's':
1518 use_syslog = 1;
1519 break;
1520 case 'h':
1521 command = DAEMON_HELP;
1522 break;
1523 case 'D':
1524 daemonize = 1;
1525 break;
1526 case 'k':
1527 command = DAEMON_KILL;
1528 break;
1529 case 'V':
1530 command = DAEMON_VERSION;
1531 break;
1532 case 'r':
1533 command = DAEMON_REFRESH;
1534 break;
1535 case 'c':
1536 command = DAEMON_CHECK;
1537 break;
1538 case 'S':
1540 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1541 fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1542 return -1;
1544 break;
1545 case 't':
1546 avahi_free(action_script);
1547 action_script = avahi_strdup(optarg);
1548 break;
1549 case 'w':
1550 wait_for_address = 1;
1551 break;
1553 case OPTION_NO_PROC_TITLE:
1554 modify_proc_title = 0;
1555 break;
1557 case OPTION_DEBUG:
1558 debug = 1;
1559 break;
1561 case OPTION_FORCE_BIND:
1562 force_bind = 1;
1563 break;
1565 case OPTION_NO_DROP_ROOT:
1566 no_drop_root = 1;
1567 break;
1569 #ifdef HAVE_CHROOT
1570 case OPTION_NO_CHROOT:
1571 no_chroot = 1;
1572 break;
1573 #endif
1575 default:
1576 return -1;
1580 if (command == DAEMON_RUN ||
1581 command == DAEMON_KILL ||
1582 command == DAEMON_REFRESH ||
1583 command == DAEMON_CHECK) {
1585 if (optind >= argc) {
1586 fprintf(stderr, "Missing interface name.\n");
1587 return -1;
1590 interface_name = avahi_strdup(argv[optind++]);
1593 if (optind != argc) {
1594 fprintf(stderr, "Too many arguments\n");
1595 return -1;
1598 if (!action_script)
1599 action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1601 return 0;
1604 static const char* pid_file_proc(void) {
1605 return pid_file_name;
1608 int main(int argc, char*argv[]) {
1609 int r = 1;
1610 char *log_ident = NULL;
1612 signal(SIGPIPE, SIG_IGN);
1614 if ((argv0 = strrchr(argv[0], '/')))
1615 argv0 = avahi_strdup(argv0 + 1);
1616 else
1617 argv0 = avahi_strdup(argv[0]);
1619 daemon_log_ident = argv0;
1621 if (parse_command_line(argc, argv) < 0)
1622 goto finish;
1624 if (modify_proc_title)
1625 avahi_init_proc_title(argc, argv);
1627 daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1628 daemon_pid_file_proc = pid_file_proc;
1629 pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1631 if (command == DAEMON_RUN) {
1632 pid_t pid;
1633 int ifindex;
1635 init_rand_seed();
1637 if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1638 daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1639 goto finish;
1642 if (getuid() != 0) {
1643 daemon_log(LOG_ERR, "This program is intended to be run as root.");
1644 goto finish;
1647 if ((pid = daemon_pid_file_is_running()) >= 0) {
1648 daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1649 goto finish;
1652 if (daemonize) {
1653 daemon_retval_init();
1655 if ((pid = daemon_fork()) < 0)
1656 goto finish;
1657 else if (pid != 0) {
1658 int ret;
1659 /** Parent **/
1661 if ((ret = daemon_retval_wait(20)) < 0) {
1662 daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1663 goto finish;
1666 r = ret;
1667 goto finish;
1670 /* Child */
1673 if (use_syslog || daemonize)
1674 daemon_log_use = DAEMON_LOG_SYSLOG;
1676 chdir("/");
1678 if (daemon_pid_file_create() < 0) {
1679 daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1681 if (daemonize)
1682 daemon_retval_send(1);
1683 goto finish;
1684 } else
1685 wrote_pid_file = 1;
1687 avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1689 if (loop(ifindex, start_address) < 0)
1690 goto finish;
1692 r = 0;
1693 } else if (command == DAEMON_HELP) {
1694 help(stdout, argv0);
1696 r = 0;
1697 } else if (command == DAEMON_VERSION) {
1698 printf("%s "PACKAGE_VERSION"\n", argv0);
1700 r = 0;
1701 } else if (command == DAEMON_KILL) {
1702 if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1703 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1704 goto finish;
1707 r = 0;
1708 } else if (command == DAEMON_REFRESH) {
1709 if (daemon_pid_file_kill(SIGHUP) < 0) {
1710 daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1711 goto finish;
1714 r = 0;
1715 } else if (command == DAEMON_CHECK)
1716 r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1719 finish:
1721 if (daemonize)
1722 daemon_retval_done();
1724 if (wrote_pid_file)
1725 daemon_pid_file_remove();
1727 avahi_free(log_ident);
1728 avahi_free(pid_file_name);
1729 avahi_free(argv0);
1730 avahi_free(interface_name);
1731 avahi_free(action_script);
1733 return r;