1 /***
2     This file is part of avahi.
3 
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.
8 
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.
13 
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
17     USA.
18 ***/
19 
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 
24 #include <sys/param.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/ioctl.h>
28 #ifdef HAVE_SYS_FILIO_H
29 #include <sys/filio.h>
30 #endif
31 #include <sys/socket.h>
32 #include <sys/wait.h>
33 #ifdef __FreeBSD__
34 #include <sys/sysctl.h>
35 #endif
36 
37 #ifdef __linux__
38 #include <netpacket/packet.h>
39 #endif
40 #include <net/ethernet.h>
41 #include <net/if.h>
42 #ifdef __FreeBSD__
43 #include <net/if_dl.h>
44 #include <net/route.h>
45 #endif
46 #include <arpa/inet.h>
47 
48 #include <assert.h>
49 #include <errno.h>
50 #include <inttypes.h>
51 #include <fcntl.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54 #include <signal.h>
55 #include <string.h>
56 #include <time.h>
57 #include <getopt.h>
58 
59 #include <grp.h>
60 #include <poll.h>
61 #include <pwd.h>
62 #include <unistd.h>
63 
64 #ifndef __linux__
65 #include <pcap.h>
66 #endif
67 
68 #include <avahi-common/malloc.h>
69 #include <avahi-common/timeval.h>
70 #include <avahi-daemon/setproctitle.h>
71 
72 #include <libdaemon/dfork.h>
73 #include <libdaemon/dsignal.h>
74 #include <libdaemon/dlog.h>
75 #include <libdaemon/dpid.h>
76 #include <libdaemon/dexec.h>
77 
78 #include "main.h"
79 #include "iface.h"
80 
81 /* An implementation of RFC 3927 */
82 
83 /* Constants from the RFC */
84 #define PROBE_WAIT 1
85 #define PROBE_NUM 3
86 #define PROBE_MIN 1
87 #define PROBE_MAX 2
88 #define ANNOUNCE_WAIT 2
89 #define ANNOUNCE_NUM 2
90 #define ANNOUNCE_INTERVAL 2
91 #define MAX_CONFLICTS 10
92 #define RATE_LIMIT_INTERVAL 60
93 #define DEFEND_INTERVAL 10
94 
95 #define IPV4LL_NETWORK 0xA9FE0000L
96 #define IPV4LL_NETMASK 0xFFFF0000L
97 #define IPV4LL_HOSTMASK 0x0000FFFFL
98 #define IPV4LL_BROADCAST 0xA9FEFFFFL
99 
100 #define ETHER_ADDRLEN 6
101 #define ETHER_HDR_SIZE (2+2*ETHER_ADDRLEN)
102 #define ARP_PACKET_SIZE (8+4+4+2*ETHER_ADDRLEN)
103 
104 typedef enum ArpOperation {
105     ARP_REQUEST = 1,
106     ARP_RESPONSE = 2
107 } ArpOperation;
108 
109 typedef struct ArpPacketInfo {
110     ArpOperation operation;
111 
112     uint32_t sender_ip_address, target_ip_address;
113     uint8_t sender_hw_address[ETHER_ADDRLEN], target_hw_address[ETHER_ADDRLEN];
114 } ArpPacketInfo;
115 
116 typedef struct ArpPacket {
117     uint8_t *ether_header;
118     uint8_t *ether_payload;
119 } ArpPacket;
120 
121 static State state = STATE_START;
122 static int n_iteration = 0;
123 static int n_conflict = 0;
124 
125 static char *interface_name = NULL;
126 static char *pid_file_name = NULL;
127 static uint32_t start_address = 0;
128 static char *argv0 = NULL;
129 static int daemonize = 0;
130 static int wait_for_address = 0;
131 static int use_syslog = 0;
132 static int debug = 0;
133 static int modify_proc_title = 1;
134 static int force_bind = 0;
135 #ifdef HAVE_CHROOT
136 static int no_chroot = 0;
137 #endif
138 static int no_drop_root = 0;
139 static int wrote_pid_file = 0;
140 static char *action_script = NULL;
141 
142 static enum {
143     DAEMON_RUN,
144     DAEMON_KILL,
145     DAEMON_REFRESH,
146     DAEMON_VERSION,
147     DAEMON_HELP,
148     DAEMON_CHECK
149 } command = DAEMON_RUN;
150 
151 typedef enum CalloutEvent {
152     CALLOUT_BIND,
153     CALLOUT_CONFLICT,
154     CALLOUT_UNBIND,
155     CALLOUT_STOP,
156     CALLOUT_MAX
157 } CalloutEvent;
158 
159 static const char * const callout_event_table[CALLOUT_MAX] = {
160     [CALLOUT_BIND] = "BIND",
161     [CALLOUT_CONFLICT] = "CONFLICT",
162     [CALLOUT_UNBIND] = "UNBIND",
163     [CALLOUT_STOP] = "STOP"
164 };
165 
166 typedef struct CalloutEventInfo {
167     CalloutEvent event;
168     uint32_t address;
169     int ifindex;
170 } CalloutEventInfo;
171 
172 #define RANDOM_DEVICE "/dev/urandom"
173 
174 #define DEBUG(x)                                \
175     do {                                        \
176         if (debug) {                            \
177             x;                                  \
178         }                                       \
179     } while (0)
180 
init_rand_seed(void)181 static void init_rand_seed(void) {
182     int fd;
183     unsigned seed = 0;
184 
185     /* Try to initialize seed from /dev/urandom, to make it a little
186      * less predictable, and to make sure that multiple machines
187      * booted at the same time choose different random seeds.  */
188     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
189         read(fd, &seed, sizeof(seed));
190         close(fd);
191     }
192 
193     /* If the initialization failed by some reason, we add the time to the seed */
194     seed ^= (unsigned) time(NULL);
195 
196     srand(seed);
197 }
198 
pick_addr(uint32_t old_addr)199 static uint32_t pick_addr(uint32_t old_addr) {
200     uint32_t addr;
201 
202     do {
203         unsigned r = (unsigned) rand();
204 
205         /* Reduce to 16 bits */
206         while (r > 0xFFFF)
207             r = (r >> 16) ^ (r & 0xFFFF);
208 
209         addr = htonl(IPV4LL_NETWORK | (uint32_t) r);
210 
211     } while (addr == old_addr || !is_ll_address(addr));
212 
213     return addr;
214 }
215 
load_address(const char * fn,uint32_t * addr)216 static int load_address(const char *fn, uint32_t *addr) {
217     FILE *f;
218     unsigned a, b, c, d;
219 
220     assert(fn);
221     assert(addr);
222 
223     if (!(f = fopen(fn, "r"))) {
224 
225         if (errno == ENOENT) {
226             *addr = 0;
227             return 0;
228         }
229 
230         daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
231         goto fail;
232     }
233 
234     if (fscanf(f, "%u.%u.%u.%u\n", &a, &b, &c, &d) != 4) {
235         daemon_log(LOG_ERR, "Parse failure");
236         goto fail;
237     }
238 
239     fclose(f);
240 
241     *addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
242     return 0;
243 
244 fail:
245     if (f)
246         fclose(f);
247 
248     return -1;
249 }
250 
save_address(const char * fn,uint32_t addr)251 static int save_address(const char *fn, uint32_t addr) {
252     FILE *f;
253     char buf[32];
254     mode_t u;
255 
256     assert(fn);
257 
258     u = umask(0033);
259     if (!(f = fopen(fn, "w"))) {
260         daemon_log(LOG_ERR, "fopen() failed: %s", strerror(errno));
261         goto fail;
262     }
263     umask(u);
264 
265     fprintf(f, "%s\n", inet_ntop(AF_INET, &addr, buf, sizeof (buf)));
266     fclose(f);
267 
268     return 0;
269 
270 fail:
271     if (f)
272         fclose(f);
273 
274     umask(u);
275 
276     return -1;
277 }
278 
279 /*
280  * Allocate a buffer with two pointers in front, one of which is
281  * guaranteed to point ETHER_HDR_SIZE bytes into it.
282  */
packet_new(size_t packet_len)283 static ArpPacket* packet_new(size_t packet_len) {
284     ArpPacket *p;
285     uint8_t *b;
286 
287     assert(packet_len > 0);
288 
289 #ifdef __linux__
290     b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + packet_len);
291     p = (ArpPacket*) b;
292     p->ether_header = NULL;
293     p->ether_payload = b + sizeof(struct ArpPacket);
294 
295 #else
296     b = avahi_new0(uint8_t, sizeof(struct ArpPacket) + ETHER_HDR_SIZE + packet_len);
297     p = (ArpPacket*) b;
298     p->ether_header = b + sizeof(struct ArpPacket);
299     p->ether_payload = b + sizeof(struct ArpPacket) + ETHER_HDR_SIZE;
300 #endif
301 
302     return p;
303 }
304 
packet_new_with_info(const ArpPacketInfo * info,size_t * packet_len)305 static ArpPacket* packet_new_with_info(const ArpPacketInfo *info, size_t *packet_len) {
306     ArpPacket *p = NULL;
307     uint8_t *r;
308 
309     assert(info);
310     assert(info->operation == ARP_REQUEST || info->operation == ARP_RESPONSE);
311     assert(packet_len != NULL);
312 
313     *packet_len = ARP_PACKET_SIZE;
314     p = packet_new(*packet_len);
315     r = p->ether_payload;
316 
317     r[1] = 1; /* HTYPE */
318     r[2] = 8; /* PTYPE */
319     r[4] = ETHER_ADDRLEN; /* HLEN */
320     r[5] = 4; /* PLEN */
321     r[7] = (uint8_t) info->operation;
322 
323     memcpy(r+8, info->sender_hw_address, ETHER_ADDRLEN);
324     memcpy(r+14, &info->sender_ip_address, 4);
325     memcpy(r+18, info->target_hw_address, ETHER_ADDRLEN);
326     memcpy(r+24, &info->target_ip_address, 4);
327 
328     return p;
329 }
330 
packet_new_probe(uint32_t ip_address,const uint8_t * hw_address,size_t * packet_len)331 static ArpPacket *packet_new_probe(uint32_t ip_address, const uint8_t*hw_address, size_t *packet_len) {
332     ArpPacketInfo info;
333 
334     memset(&info, 0, sizeof(info));
335     info.operation = ARP_REQUEST;
336     memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
337     info.target_ip_address = ip_address;
338 
339     return packet_new_with_info(&info, packet_len);
340 }
341 
packet_new_announcement(uint32_t ip_address,const uint8_t * hw_address,size_t * packet_len)342 static ArpPacket *packet_new_announcement(uint32_t ip_address, const uint8_t* hw_address, size_t *packet_len) {
343     ArpPacketInfo info;
344 
345     memset(&info, 0, sizeof(info));
346     info.operation = ARP_REQUEST;
347     memcpy(info.sender_hw_address, hw_address, ETHER_ADDRLEN);
348     info.target_ip_address = ip_address;
349     info.sender_ip_address = ip_address;
350 
351     return packet_new_with_info(&info, packet_len);
352 }
353 
packet_parse(const ArpPacket * packet,size_t packet_len,ArpPacketInfo * info)354 static int packet_parse(const ArpPacket *packet, size_t packet_len, ArpPacketInfo *info) {
355     const uint8_t *p;
356 
357     assert(packet);
358     p = (uint8_t *)packet->ether_payload;
359     assert(p);
360 
361     if (packet_len < ARP_PACKET_SIZE)
362         return -1;
363 
364     /* Check HTYPE and PTYPE */
365     if (p[0] != 0 || p[1] != 1 || p[2] != 8 || p[3] != 0)
366         return -1;
367 
368     /* Check HLEN, PLEN, OPERATION */
369     if (p[4] != ETHER_ADDRLEN || p[5] != 4 || p[6] != 0 || (p[7] != 1 && p[7] != 2))
370         return -1;
371 
372     info->operation = p[7];
373     memcpy(info->sender_hw_address, p+8, ETHER_ADDRLEN);
374     memcpy(&info->sender_ip_address, p+14, 4);
375     memcpy(info->target_hw_address, p+18, ETHER_ADDRLEN);
376     memcpy(&info->target_ip_address, p+24, 4);
377 
378     return 0;
379 }
380 
set_state(State st,int reset_counter,uint32_t address)381 static void set_state(State st, int reset_counter, uint32_t address) {
382     static const char* const state_table[] = {
383         [STATE_START] = "START",
384         [STATE_WAITING_PROBE] = "WAITING_PROBE",
385         [STATE_PROBING] = "PROBING",
386         [STATE_WAITING_ANNOUNCE] = "WAITING_ANNOUNCE",
387         [STATE_ANNOUNCING] = "ANNOUNCING",
388         [STATE_RUNNING] = "RUNNING",
389         [STATE_SLEEPING] = "SLEEPING"
390     };
391     char buf[64];
392 
393     assert(st < STATE_MAX);
394 
395     if (st == state && !reset_counter) {
396         n_iteration++;
397         DEBUG(daemon_log(LOG_DEBUG, "State iteration %s-%i", state_table[state], n_iteration));
398     } else {
399         DEBUG(daemon_log(LOG_DEBUG, "State transition %s-%i -> %s-0", state_table[state], n_iteration, state_table[st]));
400         state = st;
401         n_iteration = 0;
402     }
403 
404     if (state == STATE_SLEEPING)
405         avahi_set_proc_title(argv0, "%s: [%s] sleeping", argv0, interface_name);
406     else if (state == STATE_ANNOUNCING)
407         avahi_set_proc_title(argv0, "%s: [%s] announcing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
408     else if (state == STATE_RUNNING)
409         avahi_set_proc_title(argv0, "%s: [%s] bound %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
410     else
411         avahi_set_proc_title(argv0, "%s: [%s] probing %s", argv0, interface_name, inet_ntop(AF_INET, &address, buf, sizeof(buf)));
412 }
413 
interface_up(int iface)414 static int interface_up(int iface) {
415     int fd = -1;
416     struct ifreq ifreq;
417 
418     if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
419         daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
420         goto fail;
421     }
422 
423     memset(&ifreq, 0, sizeof(ifreq));
424     if (!if_indextoname(iface, ifreq.ifr_name)) {
425         daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
426         goto fail;
427     }
428 
429     if (ioctl(fd, SIOCGIFFLAGS, &ifreq) < 0) {
430         daemon_log(LOG_ERR, "SIOCGIFFLAGS failed: %s", strerror(errno));
431         goto fail;
432     }
433 
434     ifreq.ifr_flags |= IFF_UP;
435 
436     if (ioctl(fd, SIOCSIFFLAGS, &ifreq) < 0) {
437         daemon_log(LOG_ERR, "SIOCSIFFLAGS failed: %s", strerror(errno));
438         goto fail;
439     }
440 
441     close(fd);
442 
443     return 0;
444 
445 fail:
446     if (fd >= 0)
447         close(fd);
448 
449     return -1;
450 }
451 
452 #ifdef __linux__
453 
454 /* Linux 'packet socket' specific implementation */
455 
open_socket(int iface,uint8_t * hw_address)456 static int open_socket(int iface, uint8_t *hw_address) {
457     int fd = -1;
458     struct sockaddr_ll sa;
459     socklen_t sa_len;
460 
461     if (interface_up(iface) < 0)
462         goto fail;
463 
464     if ((fd = socket(PF_PACKET, SOCK_DGRAM, 0)) < 0) {
465         daemon_log(LOG_ERR, "socket() failed: %s", strerror(errno));
466         goto fail;
467     }
468 
469     memset(&sa, 0, sizeof(sa));
470     sa.sll_family = AF_PACKET;
471     sa.sll_protocol = htons(ETH_P_ARP);
472     sa.sll_ifindex = iface;
473 
474     if (bind(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
475         daemon_log(LOG_ERR, "bind() failed: %s", strerror(errno));
476         goto fail;
477     }
478 
479     sa_len = sizeof(sa);
480     if (getsockname(fd, (struct sockaddr*) &sa, &sa_len) < 0) {
481         daemon_log(LOG_ERR, "getsockname() failed: %s", strerror(errno));
482         goto fail;
483     }
484 
485     if (sa.sll_halen != ETHER_ADDRLEN) {
486         daemon_log(LOG_ERR, "getsockname() returned invalid hardware address.");
487         goto fail;
488     }
489 
490     memcpy(hw_address, sa.sll_addr, ETHER_ADDRLEN);
491 
492     return fd;
493 
494 fail:
495     if (fd >= 0)
496         close(fd);
497 
498     return -1;
499 }
500 
send_packet(int fd,int iface,ArpPacket * packet,size_t packet_len)501 static int send_packet(int fd, int iface, ArpPacket *packet, size_t packet_len) {
502     struct sockaddr_ll sa;
503 
504     assert(fd >= 0);
505     assert(packet);
506     assert(packet_len > 0);
507 
508     memset(&sa, 0, sizeof(sa));
509     sa.sll_family = AF_PACKET;
510     sa.sll_protocol = htons(ETH_P_ARP);
511     sa.sll_ifindex = iface;
512     sa.sll_halen = ETHER_ADDRLEN;
513     memset(sa.sll_addr, 0xFF, ETHER_ADDRLEN);
514 
515     if (sendto(fd, packet->ether_payload, packet_len, 0, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
516         daemon_log(LOG_ERR, "sendto() failed: %s", strerror(errno));
517         return -1;
518     }
519 
520     return 0;
521 }
522 
recv_packet(int fd,ArpPacket ** packet,size_t * packet_len)523 static int recv_packet(int fd, ArpPacket **packet, size_t *packet_len) {
524     int s;
525     struct sockaddr_ll sa;
526     socklen_t sa_len;
527     ssize_t r;
528 
529     assert(fd >= 0);
530     assert(packet);
531     assert(packet_len);
532 
533     *packet = NULL;
534 
535     if (ioctl(fd, FIONREAD, &s) < 0) {
536         daemon_log(LOG_ERR, "FIONREAD failed: %s", strerror(errno));
537         goto fail;
538     }
539 
540     if (s <= 0)
541         s = 4096;
542 
543     *packet = packet_new(s);
544 
545     sa_len = sizeof(sa);
546     if ((r = recvfrom(fd, (*packet)->ether_payload, s, 0, (struct sockaddr*) &sa, &sa_len)) < 0) {
547         daemon_log(LOG_ERR, "recvfrom() failed: %s", strerror(errno));
548         goto fail;
549     }
550 
551     *packet_len = (size_t) r;
552 
553     return 0;
554 
555 fail:
556     if (*packet) {
557         avahi_free(*packet);
558         *packet = NULL;
559     }
560 
561     return -1;
562 }
563 
close_socket(int fd)564 static void close_socket(int fd) {
565     close(fd);
566 }
567 
568 #else /* !__linux__ */
569 /* PCAP-based implementation */
570 
571 static pcap_t *__pp;
572 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
573 static uint8_t __lladdr[ETHER_ADDRLEN];
574 
575 #ifndef elementsof
576 #define elementsof(array)       (sizeof(array)/sizeof(array[0]))
577 #endif
578 
__get_ether_addr(int ifindex,u_char * lladdr)579 static int __get_ether_addr(int ifindex, u_char *lladdr) {
580     int mib[6];
581     char *buf;
582     struct if_msghdr *ifm;
583     char *lim;
584     char *next;
585     struct sockaddr_dl *sdl;
586     size_t len;
587 
588     mib[0] = CTL_NET;
589     mib[1] = PF_ROUTE;
590     mib[2] = 0;
591     mib[3] = 0;
592     mib[4] = NET_RT_IFLIST;
593     mib[5] = ifindex;
594 
595     if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
596         daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
597                    strerror(errno));
598         return -1;
599     }
600 
601     buf = avahi_malloc(len);
602     if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
603         daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
604                    strerror(errno));
605         free(buf);
606         return -1;
607     }
608 
609     lim = buf + len;
610     for (next = buf; next < lim; next += ifm->ifm_msglen) {
611         ifm = (struct if_msghdr *)next;
612         if (ifm->ifm_type == RTM_IFINFO) {
613             sdl = (struct sockaddr_dl *)(ifm + 1);
614             memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
615         }
616     }
617     avahi_free(buf);
618 
619     return 0;
620 }
621 
622 #define PCAP_TIMEOUT 500 /* 0.5s */
623 
open_socket(int iface,uint8_t * hw_address)624 static int open_socket(int iface, uint8_t *hw_address) {
625     struct bpf_program bpf;
626     char *filter;
627     char ifname[IFNAMSIZ];
628     pcap_t *pp;
629     int err;
630     int fd;
631 
632     assert(__pp == NULL);
633 
634     if (interface_up(iface) < 0)
635         return -1;
636 
637     if (__get_ether_addr(iface, __lladdr) == -1)
638         return -1;
639 
640     if (if_indextoname(iface, ifname) == NULL)
641         return -1;
642 
643     /*
644      * Using a timeout for BPF is fairly portable across BSDs. On most
645      * modern versions, using the timeout/nonblock/poll method results in
646      * fairly sane behavior, with the timeout only coming into play during
647      * the next_ex() call itself (so, for us, that's only when there's
648      * data). On older versions, it may result in a PCAP_TIMEOUT busy-wait
649      * on some versions, though, as the poll() may terminate at the
650      * PCAP_TIMEOUT instead of the poll() timeout.
651      */
652     pp = pcap_open_live(ifname, 1500, 0, PCAP_TIMEOUT, __pcap_errbuf);
653     if (pp == NULL) {
654         return (-1);
655     }
656     err = pcap_set_datalink(pp, DLT_EN10MB);
657     if (err == -1) {
658         daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
659         pcap_close(pp);
660         return (-1);
661     }
662     err = pcap_setdirection(pp, PCAP_D_IN);
663     if (err == -1) {
664         daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
665         pcap_close(pp);
666         return (-1);
667     }
668 
669     fd = pcap_get_selectable_fd(pp);
670     if (fd == -1) {
671         pcap_close(pp);
672         return (-1);
673     }
674 
675     /*
676      * Using setnonblock is a portability stop-gap. Using the timeout in
677      * combination with setnonblock will ensure on most BSDs that the
678      * next_ex call returns in a timely fashion.
679      */
680     err = pcap_setnonblock(pp, 1, __pcap_errbuf);
681     if (err == -1) {
682         pcap_close(pp);
683         return (-1);
684     }
685 
686     filter = avahi_strdup_printf("arp and (ether dst ff:ff:ff:ff:ff:ff or "
687                                  "%02x:%02x:%02x:%02x:%02x:%02x)",
688                                  __lladdr[0], __lladdr[1],
689                                  __lladdr[2], __lladdr[3],
690                                  __lladdr[4], __lladdr[5]);
691     DEBUG(daemon_log(LOG_DEBUG, "Using pcap filter '%s'", filter));
692 
693     err = pcap_compile(pp, &bpf, filter, 1, 0);
694     avahi_free(filter);
695     if (err == -1) {
696         daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
697         pcap_close(pp);
698         return (-1);
699     }
700     err = pcap_setfilter(pp, &bpf);
701     if (err == -1) {
702         daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
703         pcap_close(pp);
704         return (-1);
705     }
706     pcap_freecode(&bpf);
707 
708     /* Stash pcap-specific context away. */
709     memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
710     __pp = pp;
711 
712     return (fd);
713 }
714 
close_socket(int fd AVAHI_GCC_UNUSED)715 static void close_socket(int fd AVAHI_GCC_UNUSED) {
716     assert(__pp != NULL);
717     pcap_close(__pp);
718     __pp = NULL;
719 }
720 
721 /*
722  * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
723  * and prepend the required ethernet header information before sending.
724  */
send_packet(int fd AVAHI_GCC_UNUSED,int iface AVAHI_GCC_UNUSED,ArpPacket * packet,size_t packet_len)725 static int send_packet(int fd AVAHI_GCC_UNUSED, int iface AVAHI_GCC_UNUSED, ArpPacket *packet, size_t packet_len) {
726     struct ether_header *eh;
727 
728     assert(__pp != NULL);
729     assert(packet != NULL);
730 
731     eh = (struct ether_header *)packet->ether_header;
732     memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
733     memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
734     eh->ether_type = htons(0x0806);
735 
736     return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
737 }
738 
recv_packet(int fd AVAHI_GCC_UNUSED,ArpPacket ** packet,size_t * packet_len)739 static int recv_packet(int fd AVAHI_GCC_UNUSED, ArpPacket **packet, size_t *packet_len) {
740     struct pcap_pkthdr *ph;
741     u_char *pd;
742     ArpPacket *ap;
743     int err;
744     int retval;
745 
746     assert(__pp != NULL);
747     assert(packet != NULL);
748     assert(packet_len != NULL);
749 
750     *packet = NULL;
751     *packet_len = 0;
752     retval = -1;
753 
754     err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
755     if (err == 1 && ph->caplen <= ph->len) {
756         ap = packet_new(ph->caplen);
757         memcpy(ap->ether_header, pd, ph->caplen);
758         *packet = ap;
759         *packet_len = (ph->caplen - sizeof(struct ether_header));
760         retval = 0;
761     } else if (err >= 0) {
762         /*
763          * err == 1: Just drop bogus packets (>1500 for an arp packet!?)
764          * on the floor.
765          *
766          * err == 0: We might have had traffic on the pcap fd that
767          * didn't match the filter, in which case we'll get 0 packets.
768          */
769         retval = 0;
770     } else
771         daemon_log(LOG_ERR, "pcap_next_ex(%d): %s",
772                    err, pcap_geterr(__pp));
773 
774     return (retval);
775 }
776 #endif /* __linux__ */
777 
is_ll_address(uint32_t addr)778 int is_ll_address(uint32_t addr) {
779     return
780         ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
781         ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
782         ((ntohl(addr) & 0x0000FF00) != 0xFF00);
783 }
784 
elapse_time(struct timeval * tv,unsigned msec,unsigned jitter)785 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
786     assert(tv);
787 
788     gettimeofday(tv, NULL);
789 
790     if (msec)
791         avahi_timeval_add(tv, (AvahiUsec) msec*1000);
792 
793     if (jitter)
794         avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
795 
796     return tv;
797 }
798 
fork_dispatcher(void)799 static FILE* fork_dispatcher(void) {
800     FILE *ret;
801     int fds[2];
802     pid_t pid;
803 
804     if (pipe(fds) < 0) {
805         daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
806         goto fail;
807     }
808 
809     if ((pid = fork()) < 0)
810         goto fail;
811     else if (pid == 0) {
812         FILE *f = NULL;
813         int r = 1;
814 
815         /* Please note that the signal pipe is not closed at this
816          * point, signals will thus be dispatched in the main
817          * process. */
818 
819         daemon_retval_done();
820 
821         avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
822 
823         close(fds[1]);
824 
825         if (!(f = fdopen(fds[0], "r"))) {
826             daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
827             goto dispatcher_fail;
828         }
829 
830         for (;;) {
831             CalloutEventInfo info;
832             char name[IFNAMSIZ], buf[64];
833             int k;
834 
835             if (fread(&info, sizeof(info), 1, f) != 1) {
836                 if (feof(f))
837                     break;
838 
839                 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
840                 goto dispatcher_fail;
841             }
842 
843             assert(info.event <= CALLOUT_MAX);
844 
845             if (!if_indextoname(info.ifindex, name)) {
846                 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
847                 continue;
848             }
849 
850             if (daemon_exec("/", &k,
851                             action_script, action_script,
852                             callout_event_table[info.event],
853                             name,
854                             inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
855 
856                 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
857                 continue;
858             }
859 
860             if (k != 0)
861                 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
862         }
863 
864         r = 0;
865 
866     dispatcher_fail:
867 
868         if (f)
869             fclose(f);
870 
871 #ifdef HAVE_CHROOT
872         /* If the main process is trapped inside a chroot() we have to
873          * remove the PID file for it */
874 
875         if (!no_chroot && wrote_pid_file)
876             daemon_pid_file_remove();
877 #endif
878 
879         _exit(r);
880     }
881 
882     /* parent */
883 
884     close(fds[0]);
885     fds[0] = -1;
886 
887     if (!(ret = fdopen(fds[1], "w"))) {
888         daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
889         goto fail;
890     }
891 
892     return ret;
893 
894 fail:
895     if (fds[0] >= 0)
896         close(fds[0]);
897     if (fds[1] >= 0)
898         close(fds[1]);
899 
900     return NULL;
901 }
902 
do_callout(FILE * f,CalloutEvent event,int iface,uint32_t addr)903 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
904     CalloutEventInfo info;
905     char buf[64], ifname[IFNAMSIZ];
906 
907     daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
908                callout_event_table[event],
909                inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
910                if_indextoname(iface, ifname));
911 
912     info.event = event;
913     info.ifindex = iface;
914     info.address = addr;
915 
916     if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
917         daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
918         return -1;
919     }
920 
921     return 0;
922 }
923 
924 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
925 
drop_privs(void)926 static int drop_privs(void) {
927     struct passwd *pw;
928     struct group * gr;
929     int r;
930     mode_t u;
931 
932     pw = NULL;
933     gr = NULL;
934 
935     /* Get user/group ID */
936 
937     if (!no_drop_root) {
938 
939         if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
940             daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
941             return -1;
942         }
943 
944         if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
945             daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
946             return -1;
947         }
948 
949         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);
950     }
951 
952     /* Create directory */
953     u = umask(0000);
954     r = mkdir(AVAHI_IPDATA_DIR, 0755);
955     umask(u);
956 
957     if (r < 0 && errno != EEXIST) {
958         daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
959         return -1;
960     }
961 
962     /* Convey working directory */
963 
964     if (!no_drop_root) {
965         struct stat st;
966 
967         chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
968 
969         if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
970             daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
971             return -1;
972         }
973 
974         if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
975             daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
976             return -1;
977         }
978     }
979 
980 #ifdef HAVE_CHROOT
981 
982     if (!no_chroot) {
983         if (chroot(AVAHI_IPDATA_DIR) < 0) {
984             daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
985             return -1;
986         }
987 
988         daemon_log(LOG_INFO, "Successfully called chroot().");
989         chdir("/");
990 
991         /* Since we are now trapped inside a chroot we cannot remove
992          * the pid file anymore, the helper process will do that for us. */
993         wrote_pid_file = 0;
994     }
995 
996 #endif
997 
998     if (!no_drop_root) {
999 
1000         if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1001             daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1002             return -1;
1003         }
1004 
1005 #if defined(HAVE_SETRESGID)
1006         r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1007 #elif defined(HAVE_SETEGID)
1008         if ((r = setgid(gr->gr_gid)) >= 0)
1009             r = setegid(gr->gr_gid);
1010 #elif defined(HAVE_SETREGID)
1011         r = setregid(gr->gr_gid, gr->gr_gid);
1012 #else
1013 #error "No API to drop privileges"
1014 #endif
1015 
1016         if (r < 0) {
1017             daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1018             return -1;
1019         }
1020 
1021 #if defined(HAVE_SETRESUID)
1022         r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1023 #elif defined(HAVE_SETEUID)
1024         if ((r = setuid(pw->pw_uid)) >= 0)
1025             r = seteuid(pw->pw_uid);
1026 #elif defined(HAVE_SETREUID)
1027         r = setreuid(pw->pw_uid, pw->pw_uid);
1028 #else
1029 #error "No API to drop privileges"
1030 #endif
1031 
1032         if (r < 0) {
1033             daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1034             return -1;
1035         }
1036 
1037         set_env("USER", pw->pw_name);
1038         set_env("LOGNAME", pw->pw_name);
1039         set_env("HOME", pw->pw_dir);
1040 
1041         daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1042     }
1043 
1044     return 0;
1045 }
1046 
loop(int iface,uint32_t addr)1047 static int loop(int iface, uint32_t addr) {
1048     enum {
1049         FD_ARP,
1050         FD_IFACE,
1051         FD_SIGNAL,
1052         FD_MAX
1053     };
1054 
1055     int fd = -1, ret = -1;
1056     struct timeval next_wakeup;
1057     int next_wakeup_valid = 0;
1058     char buf[64];
1059     ArpPacket *in_packet = NULL;
1060     size_t in_packet_len = 0;
1061     ArpPacket *out_packet = NULL;
1062     size_t out_packet_len;
1063     uint8_t hw_address[ETHER_ADDRLEN];
1064     struct pollfd pollfds[FD_MAX];
1065     int iface_fd = -1;
1066     Event event = EVENT_NULL;
1067     int retval_sent = !daemonize;
1068     State st;
1069     FILE *dispatcher = NULL;
1070     char *address_fn = NULL;
1071     const char *p;
1072 
1073     daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP, 0);
1074 
1075     if (!(dispatcher = fork_dispatcher()))
1076         goto fail;
1077 
1078     if ((fd = open_socket(iface, hw_address)) < 0)
1079         goto fail;
1080 
1081     if ((iface_fd = iface_init(iface)) < 0)
1082         goto fail;
1083 
1084     if (drop_privs() < 0)
1085         goto fail;
1086 
1087     if (force_bind)
1088         st = STATE_START;
1089     else if (iface_get_initial_state(&st) < 0)
1090         goto fail;
1091 
1092 #ifdef HAVE_CHROOT
1093     if (!no_chroot)
1094         p = "";
1095     else
1096 #endif
1097         p = AVAHI_IPDATA_DIR;
1098 
1099     address_fn = avahi_strdup_printf(
1100             "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1101             hw_address[0], hw_address[1],
1102             hw_address[2], hw_address[3],
1103             hw_address[4], hw_address[5]);
1104 
1105     if (!addr)
1106         load_address(address_fn, &addr);
1107 
1108     if (addr && !is_ll_address(addr)) {
1109         daemon_log(LOG_WARNING, "Requested address %s is not from IPv4LL range 169.254/16 or a reserved address, ignoring.", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1110         addr = 0;
1111     }
1112 
1113     if (!addr) {
1114         int i;
1115         uint32_t a = 1;
1116 
1117         for (i = 0; i < ETHER_ADDRLEN; i++)
1118             a += hw_address[i]*(i+1);
1119 
1120         a = (a % 0xFE00) + 0x0100;
1121 
1122         addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1123     }
1124 
1125     assert(is_ll_address(addr));
1126 
1127     set_state(st, 1, addr);
1128 
1129     daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1130 
1131     if (state == STATE_SLEEPING)
1132         daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1133 
1134     if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1135         daemon_retval_send(0);
1136         retval_sent = 1;
1137     }
1138 
1139     memset(pollfds, 0, sizeof(pollfds));
1140     pollfds[FD_ARP].fd = fd;
1141     pollfds[FD_ARP].events = POLLIN;
1142     pollfds[FD_IFACE].fd = iface_fd;
1143     pollfds[FD_IFACE].events = POLLIN;
1144     pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1145     pollfds[FD_SIGNAL].events = POLLIN;
1146 
1147     for (;;) {
1148         int r, timeout;
1149         AvahiUsec usec;
1150 
1151         if (state == STATE_START) {
1152 
1153             /* First, wait a random time */
1154             set_state(STATE_WAITING_PROBE, 1, addr);
1155 
1156             elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1157             next_wakeup_valid = 1;
1158 
1159         } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1160                    (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1161 
1162             /* Send a probe */
1163             out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1164             set_state(STATE_PROBING, 0, addr);
1165 
1166             elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1167             next_wakeup_valid = 1;
1168 
1169         } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1170 
1171             /* Send the last probe */
1172             out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1173             set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1174 
1175             elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1176             next_wakeup_valid = 1;
1177 
1178         } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1179                    (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1180 
1181             /* Send announcement packet */
1182             out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1183             set_state(STATE_ANNOUNCING, 0, addr);
1184 
1185             elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1186             next_wakeup_valid = 1;
1187 
1188             if (n_iteration == 0) {
1189                 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1190                     goto fail;
1191 
1192                 n_conflict = 0;
1193             }
1194 
1195         } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1196 
1197             daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1198             set_state(STATE_RUNNING, 0, addr);
1199 
1200             next_wakeup_valid = 0;
1201 
1202             save_address(address_fn, addr);
1203 
1204             if (!retval_sent) {
1205                 daemon_retval_send(0);
1206                 retval_sent = 1;
1207             }
1208 
1209         } else if (event == EVENT_PACKET) {
1210             ArpPacketInfo info;
1211 
1212             assert(in_packet);
1213 
1214             if (packet_parse(in_packet, in_packet_len, &info) < 0)
1215                 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1216             else {
1217                 int conflict = 0;
1218 
1219                 if (info.sender_ip_address == addr) {
1220 
1221                     if (memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN)) {
1222                         /* Normal conflict */
1223                         conflict = 1;
1224                         daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1225                     } else
1226                         daemon_log(LOG_DEBUG, "Received ARP packet back on source interface. Ignoring.");
1227 
1228                 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1229                     /* Probe conflict */
1230                     conflict = info.target_ip_address == addr &&
1231                                info.sender_ip_address == 0 &&
1232                                memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1233 
1234                     if (conflict)
1235                         daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1236                 }
1237 
1238                 if (conflict) {
1239 
1240                     if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1241                         if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1242                             goto fail;
1243 
1244                     /* Pick a new address */
1245                     addr = pick_addr(addr);
1246 
1247                     daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1248 
1249                     n_conflict++;
1250 
1251                     set_state(STATE_WAITING_PROBE, 1, addr);
1252 
1253                     if (n_conflict >= MAX_CONFLICTS) {
1254                         daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1255                         elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1256                     } else
1257                         elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1258 
1259                     next_wakeup_valid = 1;
1260                 } else
1261                     DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1262             }
1263 
1264         } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED && !force_bind) {
1265 
1266             daemon_log(LOG_INFO, "A routable address has been configured.");
1267 
1268             if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1269                 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1270                     goto fail;
1271 
1272             if (!retval_sent) {
1273                 daemon_retval_send(0);
1274                 retval_sent = 1;
1275             }
1276 
1277             set_state(STATE_SLEEPING, 1, addr);
1278             next_wakeup_valid = 0;
1279 
1280         } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1281 
1282             daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1283 
1284             set_state(STATE_WAITING_PROBE, 1, addr);
1285 
1286             elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1287             next_wakeup_valid = 1;
1288 
1289         } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING) {
1290 
1291             /* The user requested a reannouncing of the address by a SIGHUP */
1292             daemon_log(LOG_INFO, "Reannouncing address.");
1293 
1294             /* Send announcement packet */
1295             out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1296             set_state(STATE_ANNOUNCING, 1, addr);
1297 
1298             elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1299             next_wakeup_valid = 1;
1300         }
1301 
1302         if (out_packet) {
1303             DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1304 
1305             if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1306                 goto fail;
1307 
1308             avahi_free(out_packet);
1309             out_packet = NULL;
1310         }
1311 
1312         if (in_packet) {
1313             avahi_free(in_packet);
1314             in_packet = NULL;
1315         }
1316 
1317         event = EVENT_NULL;
1318         timeout = -1;
1319 
1320         if (next_wakeup_valid) {
1321             usec = avahi_age(&next_wakeup);
1322             timeout = usec < 0 ? (int) (-usec/1000) : 0;
1323         }
1324 
1325         DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1326 
1327         while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1328             ;
1329 
1330         if (r < 0) {
1331             daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1332             goto fail;
1333         } else if (r == 0) {
1334             event = EVENT_TIMEOUT;
1335             next_wakeup_valid = 0;
1336         } else {
1337 
1338 
1339             if (pollfds[FD_ARP].revents) {
1340 
1341                 if (pollfds[FD_ARP].revents == POLLERR) {
1342                     /* The interface is probably down, let's recreate our socket */
1343 
1344                     close_socket(fd);
1345 
1346                     if ((fd = open_socket(iface, hw_address)) < 0)
1347                         goto fail;
1348 
1349                     pollfds[FD_ARP].fd = fd;
1350 
1351                 } else {
1352 
1353                     assert(pollfds[FD_ARP].revents == POLLIN);
1354 
1355                     if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1356                         goto fail;
1357 
1358                     if (in_packet)
1359                         event = EVENT_PACKET;
1360                 }
1361             }
1362 
1363             if (event == EVENT_NULL &&
1364                 pollfds[FD_IFACE].revents) {
1365 
1366                 assert(pollfds[FD_IFACE].revents == POLLIN);
1367 
1368                 if (iface_process(&event) < 0)
1369                     goto fail;
1370             }
1371 
1372             if (event == EVENT_NULL &&
1373                 pollfds[FD_SIGNAL].revents) {
1374 
1375                 int sig;
1376                 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1377 
1378                 if ((sig = daemon_signal_next()) <= 0) {
1379                     daemon_log(LOG_ERR, "daemon_signal_next() failed");
1380                     goto fail;
1381                 }
1382 
1383                 switch(sig) {
1384                     case SIGINT:
1385                     case SIGTERM:
1386                         daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1387                         ret = 0;
1388                         goto fail;
1389 
1390                     case SIGCHLD:
1391                         waitpid(-1, NULL, WNOHANG);
1392                         break;
1393 
1394                     case SIGHUP:
1395                         event = EVENT_REFRESH_REQUEST;
1396                         break;
1397                 }
1398 
1399             }
1400         }
1401     }
1402 
1403     ret = 0;
1404 
1405 fail:
1406 
1407     if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1408         do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1409 
1410     avahi_free(out_packet);
1411     avahi_free(in_packet);
1412 
1413     if (fd >= 0)
1414         close_socket(fd);
1415 
1416     if (iface_fd >= 0)
1417         iface_done();
1418 
1419     if (daemonize && !retval_sent)
1420         daemon_retval_send(ret);
1421 
1422     if (dispatcher)
1423         fclose(dispatcher);
1424 
1425     if (address_fn)
1426         avahi_free(address_fn);
1427 
1428     return ret;
1429 }
1430 
1431 
help(FILE * f,const char * a0)1432 static void help(FILE *f, const char *a0) {
1433     fprintf(f,
1434             "%s [options] INTERFACE\n"
1435             "    -h --help           Show this help\n"
1436             "    -D --daemonize      Daemonize after startup\n"
1437             "    -s --syslog         Write log messages to syslog(3) instead of STDERR\n"
1438             "    -k --kill           Kill a running daemon\n"
1439             "    -r --refresh        Request a running daemon refresh its IP address\n"
1440             "    -c --check          Return 0 if a daemon is already running\n"
1441             "    -V --version        Show version\n"
1442             "    -S --start=ADDRESS  Start with this address from the IPv4LL range\n"
1443             "                        169.254.0.0/16\n"
1444             "    -t --script=script  Action script to run (defaults to\n"
1445             "                        "AVAHI_IPCONF_SCRIPT")\n"
1446             "    -w --wait           Wait until an address has been acquired before\n"
1447             "                        daemonizing\n"
1448             "       --force-bind     Assign an IPv4LL address even if a routable address\n"
1449             "                        is already assigned\n"
1450             "       --no-drop-root   Don't drop privileges\n"
1451 #ifdef HAVE_CHROOT
1452             "       --no-chroot      Don't chroot()\n"
1453 #endif
1454             "       --no-proc-title  Don't modify process title\n"
1455             "       --debug          Increase verbosity\n",
1456             a0);
1457 }
1458 
parse_command_line(int argc,char * argv[])1459 static int parse_command_line(int argc, char *argv[]) {
1460     int c;
1461 
1462     enum {
1463         OPTION_NO_PROC_TITLE = 256,
1464         OPTION_FORCE_BIND,
1465         OPTION_DEBUG,
1466         OPTION_NO_DROP_ROOT,
1467 #ifdef HAVE_CHROOT
1468         OPTION_NO_CHROOT
1469 #endif
1470     };
1471 
1472     static const struct option long_options[] = {
1473         { "help",          no_argument,       NULL, 'h' },
1474         { "daemonize",     no_argument,       NULL, 'D' },
1475         { "syslog",        no_argument,       NULL, 's' },
1476         { "kill",          no_argument,       NULL, 'k' },
1477         { "refresh",       no_argument,       NULL, 'r' },
1478         { "check",         no_argument,       NULL, 'c' },
1479         { "version",       no_argument,       NULL, 'V' },
1480         { "start",         required_argument, NULL, 'S' },
1481         { "script",        required_argument, NULL, 't' },
1482         { "wait",          no_argument,       NULL, 'w' },
1483         { "force-bind",    no_argument,       NULL, OPTION_FORCE_BIND },
1484         { "no-drop-root",  no_argument,       NULL, OPTION_NO_DROP_ROOT },
1485 #ifdef HAVE_CHROOT
1486         { "no-chroot",     no_argument,       NULL, OPTION_NO_CHROOT },
1487 #endif
1488         { "no-proc-title", no_argument,       NULL, OPTION_NO_PROC_TITLE },
1489         { "debug",         no_argument,       NULL, OPTION_DEBUG },
1490         { NULL, 0, NULL, 0 }
1491     };
1492 
1493     while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1494 
1495         switch(c) {
1496             case 's':
1497                 use_syslog = 1;
1498                 break;
1499             case 'h':
1500                 command = DAEMON_HELP;
1501                 break;
1502             case 'D':
1503                 daemonize = 1;
1504                 break;
1505             case 'k':
1506                 command = DAEMON_KILL;
1507                 break;
1508             case 'V':
1509                 command = DAEMON_VERSION;
1510                 break;
1511             case 'r':
1512                 command = DAEMON_REFRESH;
1513                 break;
1514             case 'c':
1515                 command = DAEMON_CHECK;
1516                 break;
1517             case 'S':
1518 
1519                 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1520                     fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1521                     return -1;
1522                 }
1523                 break;
1524             case 't':
1525                 avahi_free(action_script);
1526                 action_script = avahi_strdup(optarg);
1527                 break;
1528             case 'w':
1529                 wait_for_address = 1;
1530                 break;
1531 
1532             case OPTION_NO_PROC_TITLE:
1533                 modify_proc_title = 0;
1534                 break;
1535 
1536             case OPTION_DEBUG:
1537                 debug = 1;
1538 #ifdef DAEMON_SET_VERBOSITY_AVAILABLE
1539                 daemon_set_verbosity(LOG_DEBUG);
1540 #endif
1541                 break;
1542 
1543             case OPTION_FORCE_BIND:
1544                 force_bind = 1;
1545                 break;
1546 
1547             case OPTION_NO_DROP_ROOT:
1548                 no_drop_root = 1;
1549                 break;
1550 
1551 #ifdef HAVE_CHROOT
1552             case OPTION_NO_CHROOT:
1553                 no_chroot = 1;
1554                 break;
1555 #endif
1556 
1557             default:
1558                 return -1;
1559         }
1560     }
1561 
1562     if (command == DAEMON_RUN ||
1563         command == DAEMON_KILL ||
1564         command == DAEMON_REFRESH ||
1565         command == DAEMON_CHECK) {
1566 
1567         if (optind >= argc) {
1568             fprintf(stderr, "Missing interface name.\n");
1569             return -1;
1570         }
1571 
1572         interface_name = avahi_strdup(argv[optind++]);
1573     }
1574 
1575     if (optind != argc) {
1576         fprintf(stderr, "Too many arguments\n");
1577         return -1;
1578     }
1579 
1580     if (!action_script)
1581         action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1582 
1583     return 0;
1584 }
1585 
pid_file_proc(void)1586 static const char* pid_file_proc(void) {
1587     return pid_file_name;
1588 }
1589 
main(int argc,char * argv[])1590 int main(int argc, char*argv[]) {
1591     int r = 1;
1592     char *log_ident = NULL;
1593 
1594     signal(SIGPIPE, SIG_IGN);
1595 
1596     if ((argv0 = strrchr(argv[0], '/')))
1597         argv0 = avahi_strdup(argv0 + 1);
1598     else
1599         argv0 = avahi_strdup(argv[0]);
1600 
1601     daemon_log_ident = argv0;
1602 
1603     if (parse_command_line(argc, argv) < 0)
1604         goto finish;
1605 
1606     if (modify_proc_title)
1607         avahi_init_proc_title(argc, argv);
1608 
1609     daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1610     daemon_pid_file_proc = pid_file_proc;
1611     pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1612 
1613     if (command == DAEMON_RUN) {
1614         pid_t pid;
1615         int ifindex;
1616 
1617         init_rand_seed();
1618 
1619         if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1620             daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1621             goto finish;
1622         }
1623 
1624         if (getuid() != 0) {
1625             daemon_log(LOG_ERR, "This program is intended to be run as root.");
1626             goto finish;
1627         }
1628 
1629         if ((pid = daemon_pid_file_is_running()) >= 0) {
1630             daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1631             goto finish;
1632         }
1633 
1634         if (daemonize) {
1635             daemon_retval_init();
1636 
1637             if ((pid = daemon_fork()) < 0)
1638                 goto finish;
1639             else if (pid != 0) {
1640                 int ret;
1641                 /** Parent **/
1642 
1643                 if ((ret = daemon_retval_wait(20)) < 0) {
1644                     daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1645                     goto finish;
1646                 }
1647 
1648                 r = ret;
1649                 goto finish;
1650             }
1651 
1652             /* Child */
1653         }
1654 
1655         if (use_syslog || daemonize)
1656             daemon_log_use = DAEMON_LOG_SYSLOG;
1657 
1658         chdir("/");
1659 
1660         if (daemon_pid_file_create() < 0) {
1661             daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1662 
1663             if (daemonize)
1664                 daemon_retval_send(1);
1665             goto finish;
1666         } else
1667             wrote_pid_file = 1;
1668 
1669         avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1670 
1671         if (loop(ifindex, start_address) < 0)
1672             goto finish;
1673 
1674         r = 0;
1675     } else if (command == DAEMON_HELP) {
1676         help(stdout, argv0);
1677 
1678         r = 0;
1679     } else if (command == DAEMON_VERSION) {
1680         printf("%s "PACKAGE_VERSION"\n", argv0);
1681 
1682         r = 0;
1683     } else if (command == DAEMON_KILL) {
1684         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1685             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1686             goto finish;
1687         }
1688 
1689         r = 0;
1690     } else if (command == DAEMON_REFRESH) {
1691         if (daemon_pid_file_kill(SIGHUP) < 0) {
1692             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1693             goto finish;
1694         }
1695 
1696         r = 0;
1697     } else if (command == DAEMON_CHECK)
1698         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1699 
1700 
1701 finish:
1702 
1703     if (daemonize)
1704         daemon_retval_done();
1705 
1706     if (wrote_pid_file)
1707         daemon_pid_file_remove();
1708 
1709     avahi_free(log_ident);
1710     avahi_free(pid_file_name);
1711     avahi_free(argv0);
1712     avahi_free(interface_name);
1713     avahi_free(action_script);
1714 
1715     return r;
1716 }
1717