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