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