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