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