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