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