]> git.meshlink.io Git - catta/blob - avahi-autoipd/main.c
get rid of a lot of old svn cruft
[catta] / avahi-autoipd / main.c
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/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
107 typedef enum ArpOperation {
108     ARP_REQUEST = 1,
109     ARP_RESPONSE = 2
110 } ArpOperation;
111
112 typedef 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
119 typedef struct ArpPacket {
120     uint8_t *ether_header;
121     uint8_t *ether_payload;
122 } ArpPacket;
123
124 static State state = STATE_START;
125 static int n_iteration = 0;
126 static int n_conflict = 0;
127
128 static char *interface_name = NULL;
129 static char *pid_file_name = NULL;
130 static uint32_t start_address = 0;
131 static char *argv0 = NULL;
132 static int daemonize = 0;
133 static int wait_for_address = 0;
134 static int use_syslog = 0;
135 static int debug = 0;
136 static int modify_proc_title = 1;
137 static int force_bind = 0;
138 #ifdef HAVE_CHROOT
139 static int no_chroot = 0;
140 #endif
141 static int no_drop_root = 0;
142 static int wrote_pid_file = 0;
143 static char *action_script = NULL;
144
145 static enum {
146     DAEMON_RUN,
147     DAEMON_KILL,
148     DAEMON_REFRESH,
149     DAEMON_VERSION,
150     DAEMON_HELP,
151     DAEMON_CHECK
152 } command = DAEMON_RUN;
153
154 typedef enum CalloutEvent {
155     CALLOUT_BIND,
156     CALLOUT_CONFLICT,
157     CALLOUT_UNBIND,
158     CALLOUT_STOP,
159     CALLOUT_MAX
160 } CalloutEvent;
161
162 static 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
169 typedef 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
184 static 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
202 static 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
219 static 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
247 fail:
248     if (f)
249         fclose(f);
250
251     return -1;
252 }
253
254 static 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
273 fail:
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  */
286 static 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
308 static 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
334 static 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
345 static 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
357 static 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
384 static 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
417 static 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
448 fail:
449     if (fd >= 0)
450         close(fd);
451
452     return -1;
453 }
454
455 #ifdef __linux__
456
457 /* Linux 'packet socket' specific implementation */
458
459 static 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
497 fail:
498     if (fd >= 0)
499         close(fd);
500
501     return -1;
502 }
503
504 static 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
526 static 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
558 fail:
559     if (*packet) {
560         avahi_free(*packet);
561         *packet = NULL;
562     }
563
564     return -1;
565 }
566
567 static void
568 close_socket(int fd) {
569     close(fd);
570 }
571
572 #else /* !__linux__ */
573 /* PCAP-based implementation */
574
575 static pcap_t *__pp;
576 static char __pcap_errbuf[PCAP_ERRBUF_SIZE];
577 static uint8_t __lladdr[ETHER_ADDRLEN];
578
579 #ifndef elementsof
580 #define elementsof(array)       (sizeof(array)/sizeof(array[0]))
581 #endif
582
583 static int
584 __get_ether_addr(int ifindex, u_char *lladdr)
585 {
586     int                      mib[6];
587     char                    *buf;
588     struct if_msghdr        *ifm;
589     char                    *lim;
590     char                    *next;
591     struct sockaddr_dl      *sdl;
592     size_t                   len;
593
594     mib[0] = CTL_NET;
595     mib[1] = PF_ROUTE;
596     mib[2] = 0;
597     mib[3] = 0;
598     mib[4] = NET_RT_IFLIST;
599     mib[5] = ifindex;
600
601     if (sysctl(mib, elementsof(mib), NULL, &len, NULL, 0) != 0) {
602         daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
603                    strerror(errno));
604         return (-1);
605     }
606
607     buf = malloc(len);
608     if (buf == NULL) {
609         daemon_log(LOG_ERR, "malloc(%d): %s", len, strerror(errno));
610         return (-1);
611     }
612
613     if (sysctl(mib, elementsof(mib), buf, &len, NULL, 0) != 0) {
614         daemon_log(LOG_ERR, "sysctl(NET_RT_IFLIST): %s",
615                    strerror(errno));
616         free(buf);
617         return (-1);
618     }
619
620     lim = buf + len;
621     for (next = buf; next < lim; next += ifm->ifm_msglen) {
622         ifm = (struct if_msghdr *)next;
623         if (ifm->ifm_type == RTM_IFINFO) {
624             sdl = (struct sockaddr_dl *)(ifm + 1);
625             memcpy(lladdr, LLADDR(sdl), ETHER_ADDRLEN);
626         }
627     }
628     free(buf);
629
630     return (0);
631 }
632
633 #define PCAP_TIMEOUT 500 /* 0.5s */
634
635 static int
636 open_socket(int iface, uint8_t *hw_address)
637 {
638     struct bpf_program       bpf;
639     char                     *filter;
640     char                     ifname[IFNAMSIZ];
641     pcap_t                  *pp;
642     int                      err;
643     int                      fd;
644
645     assert(__pp == NULL);
646
647     if (interface_up(iface) < 0) {
648         return (-1);
649     }
650     if (__get_ether_addr(iface, __lladdr) == -1) {
651         return (-1);
652     }
653     if (if_indextoname(iface, ifname) == NULL) {
654         return (-1);
655     }
656
657     /*
658      * Using a timeout for BPF is fairly portable across BSDs. On most
659      * modern versions, using the timeout/nonblock/poll method results in
660      * fairly sane behavior, with the timeout only coming into play during
661      * the next_ex() call itself (so, for us, that's only when there's
662      * data). On older versions, it may result in a PCAP_TIMEOUT busy-wait
663      * on some versions, though, as the poll() may terminate at the
664      * PCAP_TIMEOUT instead of the poll() timeout.
665      */
666     pp = pcap_open_live(ifname, 1500, 0, PCAP_TIMEOUT, __pcap_errbuf);
667     if (pp == NULL) {
668         return (-1);
669     }
670     err = pcap_set_datalink(pp, DLT_EN10MB);
671     if (err == -1) {
672         daemon_log(LOG_ERR, "pcap_set_datalink: %s", pcap_geterr(pp));
673         pcap_close(pp);
674         return (-1);
675     }
676     err = pcap_setdirection(pp, PCAP_D_IN);
677     if (err == -1) {
678         daemon_log(LOG_ERR, "pcap_setdirection: %s", pcap_geterr(pp));
679         pcap_close(pp);
680         return (-1);
681     }
682
683     fd = pcap_get_selectable_fd(pp);
684     if (fd == -1) {
685         pcap_close(pp);
686         return (-1);
687     }
688
689     /*
690      * Using setnonblock is a portability stop-gap. Using the timeout in
691      * combination with setnonblock will ensure on most BSDs that the
692      * next_ex call returns in a timely fashion.
693      */
694     err = pcap_setnonblock(pp, 1, __pcap_errbuf);
695     if (err == -1) {
696         pcap_close(pp);
697         return (-1);
698     }
699
700     filter = avahi_strdup_printf("arp and (ether dst ff:ff:ff:ff:ff:ff or "
701                                  "%02x:%02x:%02x:%02x:%02x:%02x)",
702                                  __lladdr[0], __lladdr[1],
703                                  __lladdr[2], __lladdr[3],
704                                  __lladdr[4], __lladdr[5]);
705     DEBUG(daemon_log(LOG_DEBUG, "Using pcap filter '%s'", filter));
706
707     err = pcap_compile(pp, &bpf, filter, 1, 0);
708     avahi_free(filter);
709     if (err == -1) {
710         daemon_log(LOG_ERR, "pcap_compile: %s", pcap_geterr(pp));
711         pcap_close(pp);
712         return (-1);
713     }
714     err = pcap_setfilter(pp, &bpf);
715     if (err == -1) {
716         daemon_log(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pp));
717         pcap_close(pp);
718         return (-1);
719     }
720     pcap_freecode(&bpf);
721
722     /* Stash pcap-specific context away. */
723     memcpy(hw_address, __lladdr, ETHER_ADDRLEN);
724     __pp = pp;
725
726     return (fd);
727 }
728
729 static void
730 close_socket(int fd __unused)
731 {
732
733     assert(__pp != NULL);
734     pcap_close(__pp);
735     __pp = NULL;
736 }
737
738 /*
739  * We trick avahi into allocating sizeof(packet) + sizeof(ether_header),
740  * and prepend the required ethernet header information before sending.
741  */
742 static int
743 send_packet(int fd __unused, int iface __unused, ArpPacket *packet,
744             size_t packet_len)
745 {
746     struct ether_header *eh;
747
748     assert(__pp != NULL);
749     assert(packet != NULL);
750
751     eh = (struct ether_header *)packet->ether_header;
752     memset(eh->ether_dhost, 0xFF, ETHER_ADDRLEN);
753     memcpy(eh->ether_shost, __lladdr, ETHER_ADDRLEN);
754     eh->ether_type = htons(0x0806);
755
756     return (pcap_inject(__pp, (void *)eh, packet_len + sizeof(*eh)));
757 }
758
759 static int
760 recv_packet(int fd __unused, ArpPacket **packet, size_t *packet_len)
761 {
762     struct pcap_pkthdr      *ph;
763     u_char                  *pd;
764     ArpPacket               *ap;
765     int                      err;
766     int                      retval;
767
768     assert(__pp != NULL);
769     assert(packet != NULL);
770     assert(packet_len != NULL);
771
772     *packet = NULL;
773     *packet_len = 0;
774     retval = -1;
775
776     err = pcap_next_ex(__pp, &ph, (const u_char **)&pd);
777     if (err == 1 && ph->caplen <= ph->len) {
778         ap = packet_new(ph->caplen);
779         memcpy(ap->ether_header, pd, ph->caplen);
780         *packet = ap;
781         *packet_len = (ph->caplen - sizeof(struct ether_header));
782         retval = 0;
783     } else if (err >= 0) {
784         /*
785          * err == 1: Just drop bogus packets (>1500 for an arp packet!?)
786          * on the floor.
787          *
788          * err == 0: We might have had traffic on the pcap fd that
789          * didn't match the filter, in which case we'll get 0 packets.
790          */
791         retval = 0;
792     } else {
793         daemon_log(LOG_ERR, "pcap_next_ex(%d): %s",
794                    err, pcap_geterr(__pp));
795     }
796
797     return (retval);
798 }
799 #endif /* __linux__ */
800
801 int is_ll_address(uint32_t addr) {
802     return
803         ((ntohl(addr) & IPV4LL_NETMASK) == IPV4LL_NETWORK) &&
804         ((ntohl(addr) & 0x0000FF00) != 0x0000) &&
805         ((ntohl(addr) & 0x0000FF00) != 0xFF00);
806 }
807
808 static struct timeval *elapse_time(struct timeval *tv, unsigned msec, unsigned jitter) {
809     assert(tv);
810
811     gettimeofday(tv, NULL);
812
813     if (msec)
814         avahi_timeval_add(tv, (AvahiUsec) msec*1000);
815
816     if (jitter)
817         avahi_timeval_add(tv, (AvahiUsec) (jitter*1000.0*rand()/(RAND_MAX+1.0)));
818
819     return tv;
820 }
821
822 static FILE* fork_dispatcher(void) {
823     FILE *ret;
824     int fds[2];
825     pid_t pid;
826
827     if (pipe(fds) < 0) {
828         daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
829         goto fail;
830     }
831
832     if ((pid = fork()) < 0)
833         goto fail;
834     else if (pid == 0) {
835         FILE *f = NULL;
836         int r = 1;
837
838         /* Please note that the signal pipe is not closed at this
839          * point, signals will thus be dispatched in the main
840          * process. */
841
842         daemon_retval_done();
843
844         setsid();
845
846         avahi_set_proc_title(argv0, "%s: [%s] callout dispatcher", argv0, interface_name);
847
848         close(fds[1]);
849
850         if (!(f = fdopen(fds[0], "r"))) {
851             daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
852             goto dispatcher_fail;
853         }
854
855         for (;;) {
856             CalloutEventInfo info;
857             char name[IFNAMSIZ], buf[64];
858             int k;
859
860             if (fread(&info, sizeof(info), 1, f) != 1) {
861                 if (feof(f))
862                     break;
863
864                 daemon_log(LOG_ERR, "fread() failed: %s", strerror(errno));
865                 goto dispatcher_fail;
866             }
867
868             assert(info.event <= CALLOUT_MAX);
869
870             if (!if_indextoname(info.ifindex, name)) {
871                 daemon_log(LOG_ERR, "if_indextoname() failed: %s", strerror(errno));
872                 continue;
873             }
874
875             if (daemon_exec("/", &k,
876                             action_script, action_script,
877                             callout_event_table[info.event],
878                             name,
879                             inet_ntop(AF_INET, &info.address, buf, sizeof(buf)), NULL) < 0) {
880
881                 daemon_log(LOG_ERR, "Failed to run script: %s", strerror(errno));
882                 continue;
883             }
884
885             if (k != 0)
886                 daemon_log(LOG_WARNING, "Script execution failed with return value %i", k);
887         }
888
889         r = 0;
890
891     dispatcher_fail:
892
893         if (f)
894             fclose(f);
895
896 #ifdef HAVE_CHROOT
897         /* If the main process is trapped inside a chroot() we have to
898          * remove the PID file for it */
899
900         if (!no_chroot && wrote_pid_file)
901             daemon_pid_file_remove();
902 #endif
903
904         _exit(r);
905     }
906
907     /* parent */
908
909     close(fds[0]);
910     fds[0] = -1;
911
912     if (!(ret = fdopen(fds[1], "w"))) {
913         daemon_log(LOG_ERR, "fdopen() failed: %s", strerror(errno));
914         goto fail;
915     }
916
917     return ret;
918
919 fail:
920     if (fds[0] >= 0)
921         close(fds[0]);
922     if (fds[1] >= 0)
923         close(fds[1]);
924
925     return NULL;
926 }
927
928 static int do_callout(FILE *f, CalloutEvent event, int iface, uint32_t addr) {
929     CalloutEventInfo info;
930     char buf[64], ifname[IFNAMSIZ];
931
932     daemon_log(LOG_INFO, "Callout %s, address %s on interface %s",
933                callout_event_table[event],
934                inet_ntop(AF_INET, &addr, buf, sizeof(buf)),
935                if_indextoname(iface, ifname));
936
937     info.event = event;
938     info.ifindex = iface;
939     info.address = addr;
940
941     if (fwrite(&info, sizeof(info), 1, f) != 1 || fflush(f) != 0) {
942         daemon_log(LOG_ERR, "Failed to write callout event: %s", strerror(errno));
943         return -1;
944     }
945
946     return 0;
947 }
948
949 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
950
951 static int drop_privs(void) {
952     struct passwd *pw;
953     struct group * gr;
954     int r;
955     mode_t u;
956
957     pw = NULL;
958     gr = NULL;
959
960     /* Get user/group ID */
961
962     if (!no_drop_root) {
963
964         if (!(pw = getpwnam(AVAHI_AUTOIPD_USER))) {
965             daemon_log(LOG_ERR, "Failed to find user '"AVAHI_AUTOIPD_USER"'.");
966             return -1;
967         }
968
969         if (!(gr = getgrnam(AVAHI_AUTOIPD_GROUP))) {
970             daemon_log(LOG_ERR, "Failed to find group '"AVAHI_AUTOIPD_GROUP"'.");
971             return -1;
972         }
973
974         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);
975     }
976
977     /* Create directory */
978     u = umask(0000);
979     r = mkdir(AVAHI_IPDATA_DIR, 0755);
980     umask(u);
981
982     if (r < 0 && errno != EEXIST) {
983         daemon_log(LOG_ERR, "mkdir(\""AVAHI_IPDATA_DIR"\"): %s", strerror(errno));
984         return -1;
985     }
986
987     /* Convey working directory */
988
989     if (!no_drop_root) {
990         struct stat st;
991
992         chown(AVAHI_IPDATA_DIR, pw->pw_uid, gr->gr_gid);
993
994         if (stat(AVAHI_IPDATA_DIR, &st) < 0) {
995             daemon_log(LOG_ERR, "stat(): %s\n", strerror(errno));
996             return -1;
997         }
998
999         if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1000             daemon_log(LOG_ERR, "Failed to create runtime directory "AVAHI_IPDATA_DIR".");
1001             return -1;
1002         }
1003     }
1004
1005 #ifdef HAVE_CHROOT
1006
1007     if (!no_chroot) {
1008         if (chroot(AVAHI_IPDATA_DIR) < 0) {
1009             daemon_log(LOG_ERR, "Failed to chroot(): %s", strerror(errno));
1010             return -1;
1011         }
1012
1013         daemon_log(LOG_INFO, "Successfully called chroot().");
1014         chdir("/");
1015
1016         /* Since we are now trapped inside a chroot we cannot remove
1017          * the pid file anymore, the helper process will do that for us. */
1018         wrote_pid_file = 0;
1019     }
1020
1021 #endif
1022
1023     if (!no_drop_root) {
1024
1025         if (initgroups(AVAHI_AUTOIPD_USER, gr->gr_gid) != 0) {
1026             daemon_log(LOG_ERR, "Failed to change group list: %s", strerror(errno));
1027             return -1;
1028         }
1029
1030 #if defined(HAVE_SETRESGID)
1031         r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1032 #elif defined(HAVE_SETEGID)
1033         if ((r = setgid(gr->gr_gid)) >= 0)
1034             r = setegid(gr->gr_gid);
1035 #elif defined(HAVE_SETREGID)
1036         r = setregid(gr->gr_gid, gr->gr_gid);
1037 #else
1038 #error "No API to drop privileges"
1039 #endif
1040
1041         if (r < 0) {
1042             daemon_log(LOG_ERR, "Failed to change GID: %s", strerror(errno));
1043             return -1;
1044         }
1045
1046 #if defined(HAVE_SETRESUID)
1047         r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1048 #elif defined(HAVE_SETEUID)
1049         if ((r = setuid(pw->pw_uid)) >= 0)
1050             r = seteuid(pw->pw_uid);
1051 #elif defined(HAVE_SETREUID)
1052         r = setreuid(pw->pw_uid, pw->pw_uid);
1053 #else
1054 #error "No API to drop privileges"
1055 #endif
1056
1057         if (r < 0) {
1058             daemon_log(LOG_ERR, "Failed to change UID: %s", strerror(errno));
1059             return -1;
1060         }
1061
1062         set_env("USER", pw->pw_name);
1063         set_env("LOGNAME", pw->pw_name);
1064         set_env("HOME", pw->pw_dir);
1065
1066         daemon_log(LOG_INFO, "Successfully dropped root privileges.");
1067     }
1068
1069     return 0;
1070 }
1071
1072 static int loop(int iface, uint32_t addr) {
1073     enum {
1074         FD_ARP,
1075         FD_IFACE,
1076         FD_SIGNAL,
1077         FD_MAX
1078     };
1079
1080     int fd = -1, ret = -1;
1081     struct timeval next_wakeup;
1082     int next_wakeup_valid = 0;
1083     char buf[64];
1084     ArpPacket *in_packet = NULL;
1085     size_t in_packet_len;
1086     ArpPacket *out_packet = NULL;
1087     size_t out_packet_len;
1088     uint8_t hw_address[ETHER_ADDRLEN];
1089     struct pollfd pollfds[FD_MAX];
1090     int iface_fd = -1;
1091     Event event = EVENT_NULL;
1092     int retval_sent = !daemonize;
1093     State st;
1094     FILE *dispatcher = NULL;
1095     char *address_fn = NULL;
1096     const char *p;
1097
1098     daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP,0);
1099
1100     if (!(dispatcher = fork_dispatcher()))
1101         goto fail;
1102
1103     if ((fd = open_socket(iface, hw_address)) < 0)
1104         goto fail;
1105
1106     if ((iface_fd = iface_init(iface)) < 0)
1107         goto fail;
1108
1109     if (drop_privs() < 0)
1110         goto fail;
1111
1112     if (force_bind)
1113         st = STATE_START;
1114     else if (iface_get_initial_state(&st) < 0)
1115         goto fail;
1116
1117 #ifdef HAVE_CHROOT
1118     if (!no_chroot)
1119         p = "";
1120     else
1121 #endif
1122         p = AVAHI_IPDATA_DIR;
1123
1124     address_fn = avahi_strdup_printf(
1125             "%s/%02x:%02x:%02x:%02x:%02x:%02x", p,
1126             hw_address[0], hw_address[1],
1127             hw_address[2], hw_address[3],
1128             hw_address[4], hw_address[5]);
1129
1130     if (!addr)
1131         load_address(address_fn, &addr);
1132
1133     if (addr && !is_ll_address(addr)) {
1134         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)));
1135         addr = 0;
1136     }
1137
1138     if (!addr) {
1139         int i;
1140         uint32_t a = 1;
1141
1142         for (i = 0; i < ETHER_ADDRLEN; i++)
1143             a += hw_address[i]*i;
1144
1145         a = (a % 0xFE00) + 0x0100;
1146
1147         addr = htonl(IPV4LL_NETWORK | (uint32_t) a);
1148     }
1149
1150     assert(is_ll_address(addr));
1151
1152     set_state(st, 1, addr);
1153
1154     daemon_log(LOG_INFO, "Starting with address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1155
1156     if (state == STATE_SLEEPING)
1157         daemon_log(LOG_INFO, "Routable address already assigned, sleeping.");
1158
1159     if (!retval_sent && (!wait_for_address || state == STATE_SLEEPING)) {
1160         daemon_retval_send(0);
1161         retval_sent = 1;
1162     }
1163
1164     memset(pollfds, 0, sizeof(pollfds));
1165     pollfds[FD_ARP].fd = fd;
1166     pollfds[FD_ARP].events = POLLIN;
1167     pollfds[FD_IFACE].fd = iface_fd;
1168     pollfds[FD_IFACE].events = POLLIN;
1169     pollfds[FD_SIGNAL].fd = daemon_signal_fd();
1170     pollfds[FD_SIGNAL].events = POLLIN;
1171
1172     for (;;) {
1173         int r, timeout;
1174         AvahiUsec usec;
1175
1176         if (state == STATE_START) {
1177
1178             /* First, wait a random time */
1179             set_state(STATE_WAITING_PROBE, 1, addr);
1180
1181             elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1182             next_wakeup_valid = 1;
1183
1184         } else if ((state == STATE_WAITING_PROBE && event == EVENT_TIMEOUT) ||
1185                    (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration < PROBE_NUM-2)) {
1186
1187             /* Send a probe */
1188             out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1189             set_state(STATE_PROBING, 0, addr);
1190
1191             elapse_time(&next_wakeup, PROBE_MIN*1000, (PROBE_MAX-PROBE_MIN)*1000);
1192             next_wakeup_valid = 1;
1193
1194         } else if (state == STATE_PROBING && event == EVENT_TIMEOUT && n_iteration >= PROBE_NUM-2) {
1195
1196             /* Send the last probe */
1197             out_packet = packet_new_probe(addr, hw_address, &out_packet_len);
1198             set_state(STATE_WAITING_ANNOUNCE, 1, addr);
1199
1200             elapse_time(&next_wakeup, ANNOUNCE_WAIT*1000, 0);
1201             next_wakeup_valid = 1;
1202
1203         } else if ((state == STATE_WAITING_ANNOUNCE && event == EVENT_TIMEOUT) ||
1204                    (state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration < ANNOUNCE_NUM-1)) {
1205
1206             /* Send announcement packet */
1207             out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1208             set_state(STATE_ANNOUNCING, 0, addr);
1209
1210             elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1211             next_wakeup_valid = 1;
1212
1213             if (n_iteration == 0) {
1214                 if (do_callout(dispatcher, CALLOUT_BIND, iface, addr) < 0)
1215                     goto fail;
1216
1217                 n_conflict = 0;
1218             }
1219
1220         } else if ((state == STATE_ANNOUNCING && event == EVENT_TIMEOUT && n_iteration >= ANNOUNCE_NUM-1)) {
1221
1222             daemon_log(LOG_INFO, "Successfully claimed IP address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1223             set_state(STATE_RUNNING, 0, addr);
1224
1225             next_wakeup_valid = 0;
1226
1227             save_address(address_fn, addr);
1228
1229             if (!retval_sent) {
1230                 daemon_retval_send(0);
1231                 retval_sent = 1;
1232             }
1233
1234         } else if (event == EVENT_PACKET) {
1235             ArpPacketInfo info;
1236
1237             assert(in_packet);
1238
1239             if (packet_parse(in_packet, in_packet_len, &info) < 0)
1240                 daemon_log(LOG_WARNING, "Failed to parse incoming ARP packet.");
1241             else {
1242                 int conflict = 0;
1243
1244                 if (info.sender_ip_address == addr) {
1245                     /* Normal conflict */
1246                     conflict = 1;
1247                     daemon_log(LOG_INFO, "Received conflicting normal ARP packet.");
1248                 } else if (state == STATE_WAITING_PROBE || state == STATE_PROBING || state == STATE_WAITING_ANNOUNCE) {
1249                     /* Probe conflict */
1250                     conflict = info.target_ip_address == addr && memcmp(hw_address, info.sender_hw_address, ETHER_ADDRLEN);
1251
1252                     if (conflict)
1253                         daemon_log(LOG_INFO, "Received conflicting probe ARP packet.");
1254                 }
1255
1256                 if (conflict) {
1257
1258                     if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1259                         if (do_callout(dispatcher, CALLOUT_CONFLICT, iface, addr) < 0)
1260                             goto fail;
1261
1262                     /* Pick a new address */
1263                     addr = pick_addr(addr);
1264
1265                     daemon_log(LOG_INFO, "Trying address %s", inet_ntop(AF_INET, &addr, buf, sizeof(buf)));
1266
1267                     n_conflict++;
1268
1269                     set_state(STATE_WAITING_PROBE, 1, addr);
1270
1271                     if (n_conflict >= MAX_CONFLICTS) {
1272                         daemon_log(LOG_WARNING, "Got too many conflicts, rate limiting new probes.");
1273                         elapse_time(&next_wakeup, RATE_LIMIT_INTERVAL*1000, PROBE_WAIT*1000);
1274                     } else
1275                         elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1276
1277                     next_wakeup_valid = 1;
1278                 } else
1279                     DEBUG(daemon_log(LOG_DEBUG, "Ignoring irrelevant ARP packet."));
1280             }
1281
1282         } else if (event == EVENT_ROUTABLE_ADDR_CONFIGURED && !force_bind) {
1283
1284             daemon_log(LOG_INFO, "A routable address has been configured.");
1285
1286             if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1287                 if (do_callout(dispatcher, CALLOUT_UNBIND, iface, addr) < 0)
1288                     goto fail;
1289
1290             if (!retval_sent) {
1291                 daemon_retval_send(0);
1292                 retval_sent = 1;
1293             }
1294
1295             set_state(STATE_SLEEPING, 1, addr);
1296             next_wakeup_valid = 0;
1297
1298         } else if (event == EVENT_ROUTABLE_ADDR_UNCONFIGURED && state == STATE_SLEEPING && !force_bind) {
1299
1300             daemon_log(LOG_INFO, "No longer a routable address configured, restarting probe process.");
1301
1302             set_state(STATE_WAITING_PROBE, 1, addr);
1303
1304             elapse_time(&next_wakeup, 0, PROBE_WAIT*1000);
1305             next_wakeup_valid = 1;
1306
1307         } else if (event == EVENT_REFRESH_REQUEST && state == STATE_RUNNING) {
1308
1309             /* The user requested a reannouncing of the address by a SIGHUP */
1310             daemon_log(LOG_INFO, "Reannouncing address.");
1311
1312             /* Send announcement packet */
1313             out_packet = packet_new_announcement(addr, hw_address, &out_packet_len);
1314             set_state(STATE_ANNOUNCING, 1, addr);
1315
1316             elapse_time(&next_wakeup, ANNOUNCE_INTERVAL*1000, 0);
1317             next_wakeup_valid = 1;
1318         }
1319
1320         if (out_packet) {
1321             DEBUG(daemon_log(LOG_DEBUG, "sending..."));
1322
1323             if (send_packet(fd, iface, out_packet, out_packet_len) < 0)
1324                 goto fail;
1325
1326             avahi_free(out_packet);
1327             out_packet = NULL;
1328         }
1329
1330         if (in_packet) {
1331             avahi_free(in_packet);
1332             in_packet = NULL;
1333         }
1334
1335         event = EVENT_NULL;
1336         timeout = -1;
1337
1338         if (next_wakeup_valid) {
1339             usec = avahi_age(&next_wakeup);
1340             timeout = usec < 0 ? (int) (-usec/1000) : 0;
1341         }
1342
1343         DEBUG(daemon_log(LOG_DEBUG, "sleeping %ims", timeout));
1344
1345         while ((r = poll(pollfds, FD_MAX, timeout)) < 0 && errno == EINTR)
1346             ;
1347
1348         if (r < 0) {
1349             daemon_log(LOG_ERR, "poll() failed: %s", strerror(r));
1350             goto fail;
1351         } else if (r == 0) {
1352             event = EVENT_TIMEOUT;
1353             next_wakeup_valid = 0;
1354         } else {
1355
1356
1357             if (pollfds[FD_ARP].revents) {
1358
1359                 if (pollfds[FD_ARP].revents == POLLERR) {
1360                     /* The interface is probably down, let's recreate our socket */
1361
1362                     close_socket(fd);
1363
1364                     if ((fd = open_socket(iface, hw_address)) < 0)
1365                         goto fail;
1366
1367                     pollfds[FD_ARP].fd = fd;
1368
1369                 } else {
1370
1371                     assert(pollfds[FD_ARP].revents == POLLIN);
1372
1373                     if (recv_packet(fd, &in_packet, &in_packet_len) < 0)
1374                         goto fail;
1375
1376                     if (in_packet)
1377                         event = EVENT_PACKET;
1378                 }
1379             }
1380
1381             if (event == EVENT_NULL &&
1382                 pollfds[FD_IFACE].revents) {
1383
1384                 assert(pollfds[FD_IFACE].revents == POLLIN);
1385
1386                 if (iface_process(&event) < 0)
1387                     goto fail;
1388             }
1389
1390             if (event == EVENT_NULL &&
1391                 pollfds[FD_SIGNAL].revents) {
1392
1393                 int sig;
1394                 assert(pollfds[FD_SIGNAL].revents == POLLIN);
1395
1396                 if ((sig = daemon_signal_next()) <= 0) {
1397                     daemon_log(LOG_ERR, "daemon_signal_next() failed");
1398                     goto fail;
1399                 }
1400
1401                 switch(sig) {
1402                     case SIGINT:
1403                     case SIGTERM:
1404                         daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
1405                         ret = 0;
1406                         goto fail;
1407
1408                     case SIGCHLD:
1409                         waitpid(-1, NULL, WNOHANG);
1410                         break;
1411
1412                     case SIGHUP:
1413                         event = EVENT_REFRESH_REQUEST;
1414                         break;
1415                 }
1416
1417             }
1418         }
1419     }
1420
1421     ret = 0;
1422
1423 fail:
1424
1425     if (state == STATE_RUNNING || state == STATE_ANNOUNCING)
1426         do_callout(dispatcher, CALLOUT_STOP, iface, addr);
1427
1428     avahi_free(out_packet);
1429     avahi_free(in_packet);
1430
1431     if (fd >= 0)
1432         close_socket(fd);
1433
1434     if (iface_fd >= 0)
1435         iface_done();
1436
1437     if (daemonize && !retval_sent)
1438         daemon_retval_send(ret);
1439
1440     if (dispatcher)
1441         fclose(dispatcher);
1442
1443     if (address_fn)
1444         avahi_free(address_fn);
1445
1446     return ret;
1447 }
1448
1449
1450 static void help(FILE *f, const char *a0) {
1451     fprintf(f,
1452             "%s [options] INTERFACE\n"
1453             "    -h --help           Show this help\n"
1454             "    -D --daemonize      Daemonize after startup\n"
1455             "    -s --syslog         Write log messages to syslog(3) instead of STDERR\n"
1456             "    -k --kill           Kill a running daemon\n"
1457             "    -r --refresh        Request a running daemon refresh its IP address\n"
1458             "    -c --check          Return 0 if a daemon is already running\n"
1459             "    -V --version        Show version\n"
1460             "    -S --start=ADDRESS  Start with this address from the IPv4LL range\n"
1461             "                        169.254.0.0/16\n"
1462             "    -t --script=script  Action script to run (defaults to\n"
1463             "                        "AVAHI_IPCONF_SCRIPT")\n"
1464             "    -w --wait           Wait until an address has been acquired before\n"
1465             "                        daemonizing\n"
1466             "       --force-bind     Assign an IPv4LL address even if a routable address\n"
1467             "                        is already assigned\n"
1468             "       --no-drop-root   Don't drop privileges\n"
1469 #ifdef HAVE_CHROOT
1470             "       --no-chroot      Don't chroot()\n"
1471 #endif
1472             "       --no-proc-title  Don't modify process title\n"
1473             "       --debug          Increase verbosity\n",
1474             a0);
1475 }
1476
1477 static int parse_command_line(int argc, char *argv[]) {
1478     int c;
1479
1480     enum {
1481         OPTION_NO_PROC_TITLE = 256,
1482         OPTION_FORCE_BIND,
1483         OPTION_DEBUG,
1484         OPTION_NO_DROP_ROOT,
1485 #ifdef HAVE_CHROOT
1486         OPTION_NO_CHROOT
1487 #endif
1488     };
1489
1490     static const struct option long_options[] = {
1491         { "help",          no_argument,       NULL, 'h' },
1492         { "daemonize",     no_argument,       NULL, 'D' },
1493         { "syslog",        no_argument,       NULL, 's' },
1494         { "kill",          no_argument,       NULL, 'k' },
1495         { "refresh",       no_argument,       NULL, 'r' },
1496         { "check",         no_argument,       NULL, 'c' },
1497         { "version",       no_argument,       NULL, 'V' },
1498         { "start",         required_argument, NULL, 'S' },
1499         { "script",        required_argument, NULL, 't' },
1500         { "wait",          no_argument,       NULL, 'w' },
1501         { "force-bind",    no_argument,       NULL, OPTION_FORCE_BIND },
1502         { "no-drop-root",  no_argument,       NULL, OPTION_NO_DROP_ROOT },
1503 #ifdef HAVE_CHROOT
1504         { "no-chroot",     no_argument,       NULL, OPTION_NO_CHROOT },
1505 #endif
1506         { "no-proc-title", no_argument,       NULL, OPTION_NO_PROC_TITLE },
1507         { "debug",         no_argument,       NULL, OPTION_DEBUG },
1508         { NULL, 0, NULL, 0 }
1509     };
1510
1511     while ((c = getopt_long(argc, argv, "hDskrcVS:t:w", long_options, NULL)) >= 0) {
1512
1513         switch(c) {
1514             case 's':
1515                 use_syslog = 1;
1516                 break;
1517             case 'h':
1518                 command = DAEMON_HELP;
1519                 break;
1520             case 'D':
1521                 daemonize = 1;
1522                 break;
1523             case 'k':
1524                 command = DAEMON_KILL;
1525                 break;
1526             case 'V':
1527                 command = DAEMON_VERSION;
1528                 break;
1529             case 'r':
1530                 command = DAEMON_REFRESH;
1531                 break;
1532             case 'c':
1533                 command = DAEMON_CHECK;
1534                 break;
1535             case 'S':
1536
1537                 if ((start_address = inet_addr(optarg)) == (uint32_t) -1) {
1538                     fprintf(stderr, "Failed to parse IP address '%s'.", optarg);
1539                     return -1;
1540                 }
1541                 break;
1542             case 't':
1543                 avahi_free(action_script);
1544                 action_script = avahi_strdup(optarg);
1545                 break;
1546             case 'w':
1547                 wait_for_address = 1;
1548                 break;
1549
1550             case OPTION_NO_PROC_TITLE:
1551                 modify_proc_title = 0;
1552                 break;
1553
1554             case OPTION_DEBUG:
1555                 debug = 1;
1556                 break;
1557
1558             case OPTION_FORCE_BIND:
1559                 force_bind = 1;
1560                 break;
1561
1562             case OPTION_NO_DROP_ROOT:
1563                 no_drop_root = 1;
1564                 break;
1565
1566 #ifdef HAVE_CHROOT
1567             case OPTION_NO_CHROOT:
1568                 no_chroot = 1;
1569                 break;
1570 #endif
1571
1572             default:
1573                 return -1;
1574         }
1575     }
1576
1577     if (command == DAEMON_RUN ||
1578         command == DAEMON_KILL ||
1579         command == DAEMON_REFRESH ||
1580         command == DAEMON_CHECK) {
1581
1582         if (optind >= argc) {
1583             fprintf(stderr, "Missing interface name.\n");
1584             return -1;
1585         }
1586
1587         interface_name = avahi_strdup(argv[optind++]);
1588     }
1589
1590     if (optind != argc) {
1591         fprintf(stderr, "Too many arguments\n");
1592         return -1;
1593     }
1594
1595     if (!action_script)
1596         action_script = avahi_strdup(AVAHI_IPCONF_SCRIPT);
1597
1598     return 0;
1599 }
1600
1601 static const char* pid_file_proc(void) {
1602     return pid_file_name;
1603 }
1604
1605 int main(int argc, char*argv[]) {
1606     int r = 1;
1607     char *log_ident = NULL;
1608
1609     signal(SIGPIPE, SIG_IGN);
1610
1611     if ((argv0 = strrchr(argv[0], '/')))
1612         argv0 = avahi_strdup(argv0 + 1);
1613     else
1614         argv0 = avahi_strdup(argv[0]);
1615
1616     daemon_log_ident = argv0;
1617
1618     if (parse_command_line(argc, argv) < 0)
1619         goto finish;
1620
1621     if (modify_proc_title)
1622         avahi_init_proc_title(argc, argv);
1623
1624     daemon_log_ident = log_ident = avahi_strdup_printf("%s(%s)", argv0, interface_name);
1625     daemon_pid_file_proc = pid_file_proc;
1626     pid_file_name = avahi_strdup_printf(AVAHI_RUNTIME_DIR"/avahi-autoipd.%s.pid", interface_name);
1627
1628     if (command == DAEMON_RUN) {
1629         pid_t pid;
1630         int ifindex;
1631
1632         init_rand_seed();
1633
1634         if ((ifindex = if_nametoindex(interface_name)) <= 0) {
1635             daemon_log(LOG_ERR, "Failed to get index for interface name '%s': %s", interface_name, strerror(errno));
1636             goto finish;
1637         }
1638
1639         if (getuid() != 0) {
1640             daemon_log(LOG_ERR, "This program is intended to be run as root.");
1641             goto finish;
1642         }
1643
1644         if ((pid = daemon_pid_file_is_running()) >= 0) {
1645             daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
1646             goto finish;
1647         }
1648
1649         if (daemonize) {
1650             daemon_retval_init();
1651
1652             if ((pid = daemon_fork()) < 0)
1653                 goto finish;
1654             else if (pid != 0) {
1655                 int ret;
1656                 /** Parent **/
1657
1658                 if ((ret = daemon_retval_wait(20)) < 0) {
1659                     daemon_log(LOG_ERR, "Could not receive return value from daemon process.");
1660                     goto finish;
1661                 }
1662
1663                 r = ret;
1664                 goto finish;
1665             }
1666
1667             /* Child */
1668         }
1669
1670         if (use_syslog || daemonize)
1671             daemon_log_use = DAEMON_LOG_SYSLOG;
1672
1673         chdir("/");
1674
1675         if (daemon_pid_file_create() < 0) {
1676             daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
1677
1678             if (daemonize)
1679                 daemon_retval_send(1);
1680             goto finish;
1681         } else
1682             wrote_pid_file = 1;
1683
1684         avahi_set_proc_title(argv0, "%s: [%s] starting up", argv0, interface_name);
1685
1686         if (loop(ifindex, start_address) < 0)
1687             goto finish;
1688
1689         r = 0;
1690     } else if (command == DAEMON_HELP) {
1691         help(stdout, argv0);
1692
1693         r = 0;
1694     } else if (command == DAEMON_VERSION) {
1695         printf("%s "PACKAGE_VERSION"\n", argv0);
1696
1697         r = 0;
1698     } else if (command == DAEMON_KILL) {
1699         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1700             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1701             goto finish;
1702         }
1703
1704         r = 0;
1705     } else if (command == DAEMON_REFRESH) {
1706         if (daemon_pid_file_kill(SIGHUP) < 0) {
1707             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
1708             goto finish;
1709         }
1710
1711         r = 0;
1712     } else if (command == DAEMON_CHECK)
1713         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1714
1715
1716 finish:
1717
1718     if (daemonize)
1719         daemon_retval_done();
1720
1721     if (wrote_pid_file)
1722         daemon_pid_file_remove();
1723
1724     avahi_free(log_ident);
1725     avahi_free(pid_file_name);
1726     avahi_free(argv0);
1727     avahi_free(interface_name);
1728     avahi_free(action_script);
1729
1730     return r;
1731 }