]> git.meshlink.io Git - catta/blob - avahi-core/server.c
e9289da0388e3c6d4c4336623e922adc6584b0c4
[catta] / avahi-core / server.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/socket.h>
27 #include <arpa/inet.h>
28 #include <string.h>
29 #include <sys/utsname.h>
30 #include <unistd.h>
31
32 #include "server.h"
33 #include "util.h"
34 #include "iface.h"
35 #include "socket.h"
36 #include "subscribe.h"
37
38 static void free_entry(AvahiServer*s, AvahiEntry *e) {
39     AvahiEntry *t;
40
41     g_assert(s);
42     g_assert(e);
43
44     avahi_goodbye_entry(s, e, TRUE);
45
46     /* Remove from linked list */
47     AVAHI_LLIST_REMOVE(AvahiEntry, entries, s->entries, e);
48
49     /* Remove from hash table indexed by name */
50     t = g_hash_table_lookup(s->entries_by_key, e->record->key);
51     AVAHI_LLIST_REMOVE(AvahiEntry, by_key, t, e);
52     if (t)
53         g_hash_table_replace(s->entries_by_key, t->record->key, t);
54     else
55         g_hash_table_remove(s->entries_by_key, e->record->key);
56
57     /* Remove from associated group */
58     if (e->group)
59         AVAHI_LLIST_REMOVE(AvahiEntry, by_group, e->group->entries, e);
60
61     avahi_record_unref(e->record);
62     g_free(e);
63 }
64
65 static void free_group(AvahiServer *s, AvahiEntryGroup *g) {
66     g_assert(s);
67     g_assert(g);
68
69     while (g->entries)
70         free_entry(s, g->entries);
71
72     AVAHI_LLIST_REMOVE(AvahiEntryGroup, groups, s->groups, g);
73     g_free(g);
74 }
75
76 static void cleanup_dead(AvahiServer *s) {
77     AvahiEntryGroup *g, *ng;
78     AvahiEntry *e, *ne;
79     g_assert(s);
80
81
82     if (s->need_group_cleanup) {
83         for (g = s->groups; g; g = ng) {
84             ng = g->groups_next;
85             
86             if (g->dead)
87                 free_group(s, g);
88         }
89
90         s->need_group_cleanup = FALSE;
91     }
92
93     if (s->need_entry_cleanup) {
94         for (e = s->entries; e; e = ne) {
95             ne = e->entries_next;
96             
97             if (e->dead)
98                 free_entry(s, e);
99         }
100
101         s->need_entry_cleanup = FALSE;
102     }
103 }
104
105 static void send_unicast_response_packet(AvahiServer *s, AvahiInterface *i, const AvahiAddress *a, guint16 port) {
106     g_assert(s);
107     g_assert(a);
108     g_assert(port > 0);
109     g_assert(s->unicast_packet);
110
111     if (avahi_dns_packet_get_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT) != 0)
112         avahi_interface_send_packet_unicast(i, s->unicast_packet, a, port);
113
114     avahi_dns_packet_free(s->unicast_packet);
115     s->unicast_packet = NULL;
116 }
117
118 static void post_response(AvahiServer *s, AvahiDnsPacket *p, AvahiInterface *i, const AvahiAddress *a, guint16 port, AvahiRecord *r, gboolean flush_cache, gboolean legacy_unicast, gboolean unicast_response) {
119     g_assert(s);
120     g_assert(a);
121     g_assert(port > 0);
122     g_assert(r);
123
124     if (legacy_unicast) {
125
126         /* Respond with a legacy unicast packet */
127         
128         if (!(s->unicast_packet))
129             s->unicast_packet = avahi_dns_packet_new_reply(p, 512 /* unicast DNS maximum packet size is 512 */ , TRUE, TRUE);
130
131         if (avahi_dns_packet_append_record(s->unicast_packet, r, FALSE, 10))
132
133             /* Increment the ANCOUNT field */
134             
135             avahi_dns_packet_set_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT,
136                                        avahi_dns_packet_get_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT)+1);
137
138         /* If there's no space left for this response we simply don't send it */
139         
140     } else {
141
142         if (!avahi_interface_post_response(i, a, r, flush_cache, FALSE) && unicast_response) {
143             
144             /* Due to some reasons the record has not been scheduled.
145              * The client requested an unicast response in that
146              * case. Therefore we prepare such a response */
147
148             for (;;) {
149                 
150                 if (!(s->unicast_packet))
151                     s->unicast_packet = avahi_dns_packet_new_reply(p, i->hardware->mtu, FALSE, FALSE);
152                 
153                 if (avahi_dns_packet_append_record(s->unicast_packet, r, flush_cache, 0)) {
154
155                     /* Appending this record succeeded, so incremeant
156                      * the specific header field, and return to the caller */
157                     
158                     avahi_dns_packet_set_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT,
159                                                avahi_dns_packet_get_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT)+1);
160
161                     break;
162                 }
163
164                 if (avahi_dns_packet_get_field(s->unicast_packet, AVAHI_DNS_FIELD_ANCOUNT) == 0) {
165                     g_warning("Record too large, doesn't fit in any packet!");
166                     return;
167                 }
168
169                 /* Appending the record didn't succeeed, so let's send this packet, and create a new one */
170
171                 send_unicast_response_packet(s, i, a, port);
172                 
173                 avahi_dns_packet_free(s->unicast_packet);
174                 s->unicast_packet = NULL;
175             }
176             
177         }
178     }
179 }
180
181 static void handle_query_key(AvahiServer *s, AvahiDnsPacket *p, AvahiKey *k, AvahiInterface *i, const AvahiAddress *a, guint16 port, gboolean legacy_unicast, gboolean unicast_response) {
182     AvahiEntry *e;
183     gchar *txt;
184     
185     g_assert(s);
186     g_assert(k);
187     g_assert(i);
188     g_assert(a);
189
190     g_message("Handling query: %s", txt = avahi_key_to_string(k));
191     g_free(txt);
192
193     avahi_packet_scheduler_incoming_query(i->scheduler, k);
194
195     if (k->type == AVAHI_DNS_TYPE_ANY) {
196
197         /* Handle ANY query */
198         
199         for (e = s->entries; e; e = e->entries_next)
200             if (!e->dead && avahi_key_pattern_match(k, e->record->key) && avahi_entry_registered(s, e, i))
201                 post_response(s, p, i, a, port, e->record, e->flags & AVAHI_ENTRY_UNIQUE, legacy_unicast, unicast_response);
202
203     } else {
204
205         /* Handle all other queries */
206         
207         for (e = g_hash_table_lookup(s->entries_by_key, k); e; e = e->by_key_next)
208             if (!e->dead && avahi_entry_registered(s, e, i))
209                 post_response(s, p, i, a, port, e->record, e->flags & AVAHI_ENTRY_UNIQUE, legacy_unicast, unicast_response);
210     }
211 }
212
213 static void withdraw_entry(AvahiServer *s, AvahiEntry *e) {
214     g_assert(s);
215     g_assert(e);
216
217     
218     if (e->group) {
219         AvahiEntry *k;
220         
221         for (k = e->group->entries; k; k = k->by_group_next) {
222             avahi_goodbye_entry(s, k, FALSE);
223             k->dead = TRUE;
224         }
225         
226         avahi_entry_group_change_state(e->group, AVAHI_ENTRY_GROUP_COLLISION);
227     } else {
228         avahi_goodbye_entry(s, e, FALSE);
229         e->dead = TRUE;
230     }
231
232     s->need_entry_cleanup = TRUE;
233 }
234
235 static void incoming_probe(AvahiServer *s, AvahiRecord *record, AvahiInterface *i) {
236     AvahiEntry *e, *n;
237     gchar *t;
238     
239     g_assert(s);
240     g_assert(record);
241     g_assert(i);
242
243     t = avahi_record_to_string(record);
244
245 /*     g_message("PROBE: [%s]", t); */
246     
247     for (e = g_hash_table_lookup(s->entries_by_key, record->key); e; e = n) {
248         n = e->by_key_next;
249
250         if (e->dead || avahi_record_equal_no_ttl(record, e->record))
251             continue;
252
253         if (avahi_entry_registering(s, e, i)) {
254             gint cmp;
255
256             if ((cmp = avahi_record_lexicographical_compare(record, e->record)) > 0) {
257                 withdraw_entry(s, e);
258                 g_message("Recieved conflicting probe [%s]. Local host lost. Withdrawing.", t);
259             } else if (cmp < 0)
260                 g_message("Recieved conflicting probe [%s]. Local host won.", t);
261
262         }
263     }
264
265     g_free(t);
266 }
267
268 static gboolean handle_conflict(AvahiServer *s, AvahiInterface *i, AvahiRecord *record, gboolean unique, const AvahiAddress *a) {
269     gboolean valid = TRUE;
270     AvahiEntry *e, *n;
271     gchar *t;
272     
273     g_assert(s);
274     g_assert(i);
275     g_assert(record);
276
277     t = avahi_record_to_string(record);
278
279 /*     g_message("CHECKING FOR CONFLICT: [%s]", t); */
280
281     for (e = g_hash_table_lookup(s->entries_by_key, record->key); e; e = n) {
282         n = e->by_key_next;
283
284         if (e->dead)
285             continue;
286         
287         if (avahi_entry_registered(s, e, i)) {
288
289             gboolean equal = avahi_record_equal_no_ttl(record, e->record);
290                 
291             /* Check whether there is a unique record conflict */
292             if (!equal && ((e->flags & AVAHI_ENTRY_UNIQUE) || unique)) {
293                 gint cmp;
294                 
295                 /* The lexicographically later data wins. */
296                 if ((cmp = avahi_record_lexicographical_compare(record, e->record)) > 0) {
297                     g_message("Recieved conflicting record [%s]. Local host lost. Withdrawing.", t);
298                     withdraw_entry(s, e);
299                 } else if (cmp < 0) {
300                     /* Tell the other host that our entry is lexicographically later */
301
302                     g_message("Recieved conflicting record [%s]. Local host won. Refreshing.", t);
303
304                     valid = FALSE;
305                     avahi_interface_post_response(i, a, e->record, e->flags & AVAHI_ENTRY_UNIQUE, TRUE);
306                 }
307                 
308                 /* Check wheter there is a TTL conflict */
309             } else if (equal && record->ttl <= e->record->ttl/2) {
310                 /* Correct the TTL */
311                 valid = FALSE;
312                 avahi_interface_post_response(i, a, e->record, e->flags & AVAHI_ENTRY_UNIQUE, TRUE);
313                 g_message("Recieved record with bad TTL [%s]. Refreshing.", t);
314             }
315             
316         } else if (avahi_entry_registering(s, e, i)) {
317
318             if (!avahi_record_equal_no_ttl(record, e->record) && ((e->flags & AVAHI_ENTRY_UNIQUE) || unique)) {
319
320                 /* We are currently registering a matching record, but
321                  * someone else already claimed it, so let's
322                  * withdraw */
323                 
324                 g_message("Recieved conflicting record [%s] with local record to be. Withdrawing.", t);
325                 withdraw_entry(s, e);
326             }
327         }
328     }
329
330     g_free(t);
331
332     return valid;
333 }
334
335 static void incoming_known_answer(AvahiServer *s, AvahiInterface *i, AvahiRecord *r, gboolean legacy_unicast, gboolean unique, const AvahiAddress *a) {
336     g_assert(s);
337     g_assert(i);
338     g_assert(r);
339     
340     if (legacy_unicast)
341         return;
342
343     if (handle_conflict(s, i, r, unique, a))
344         avahi_packet_scheduler_incoming_known_answer(i->scheduler, r, a);
345 }
346
347 static void handle_query(AvahiServer *s, AvahiDnsPacket *p, AvahiInterface *i, const AvahiAddress *a, guint16 port, gboolean legacy_unicast) {
348     guint n;
349     
350     g_assert(s);
351     g_assert(p);
352     g_assert(i);
353     g_assert(a);
354
355     g_assert(!s->unicast_packet);
356
357     /* Handle the questions */
358     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT); n > 0; n --) {
359         AvahiKey *key;
360         gboolean unicast_response = FALSE;
361
362         if (!(key = avahi_dns_packet_consume_key(p, &unicast_response))) {
363             g_warning("Packet too short (1)");
364             return;
365         }
366
367         handle_query_key(s, p, key, i, a, port, legacy_unicast, unicast_response);
368         avahi_key_unref(key);
369     }
370
371     /* Known Answer Suppression */
372     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT); n > 0; n --) {
373         AvahiRecord *record;
374         gboolean unique = FALSE;
375
376         if (!(record = avahi_dns_packet_consume_record(p, &unique))) {
377             g_warning("Packet too short (2)");
378             return;
379         }
380
381         incoming_known_answer(s, i, record, legacy_unicast, unique, a);
382         avahi_record_unref(record);
383     }
384
385     /* Probe record */
386     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT); n > 0; n --) {
387         AvahiRecord *record;
388         gboolean unique = FALSE;
389
390         if (!(record = avahi_dns_packet_consume_record(p, &unique))) {
391             g_warning("Packet too short (3)");
392             return;
393         }
394
395         if (record->key->type != AVAHI_DNS_TYPE_ANY)
396             incoming_probe(s, record, i);
397         
398         avahi_record_unref(record);
399     }
400
401     if (s->unicast_packet)
402         send_unicast_response_packet(s, i, a, port);
403 }
404
405 static void handle_response(AvahiServer *s, AvahiDnsPacket *p, AvahiInterface *i, const AvahiAddress *a) {
406     guint n;
407     
408     g_assert(s);
409     g_assert(p);
410     g_assert(i);
411     g_assert(a);
412     
413     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) +
414              avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT); n > 0; n--) {
415         AvahiRecord *record;
416         gboolean cache_flush = FALSE;
417         gchar *txt;
418         
419         if (!(record = avahi_dns_packet_consume_record(p, &cache_flush))) {
420             g_warning("Packet too short (4)");
421             return;
422         }
423
424         if (record->key->type != AVAHI_DNS_TYPE_ANY) {
425
426             g_message("Handling response: %s", txt = avahi_record_to_string(record));
427             g_free(txt);
428             
429             if (handle_conflict(s, i, record, cache_flush, a)) {
430                 avahi_cache_update(i->cache, record, cache_flush, a);
431                 avahi_packet_scheduler_incoming_response(i->scheduler, record);
432             }
433         }
434             
435         avahi_record_unref(record);
436     }
437 }
438
439 static void dispatch_packet(AvahiServer *s, AvahiDnsPacket *p, struct sockaddr *sa, gint iface, gint ttl) {
440     AvahiInterface *i;
441     AvahiAddress a;
442     guint16 port;
443     
444     g_assert(s);
445     g_assert(p);
446     g_assert(sa);
447     g_assert(iface > 0);
448
449     if (!(i = avahi_interface_monitor_get_interface(s->monitor, iface, sa->sa_family))) {
450         g_warning("Recieved packet from invalid interface.");
451         return;
452     }
453
454     g_message("new packet recieved on interface '%s.%i'.", i->hardware->name, i->protocol);
455
456     if (sa->sa_family == AF_INET6) {
457         static const guint8 ipv4_in_ipv6[] = {
458             0x00, 0x00, 0x00, 0x00,
459             0x00, 0x00, 0x00, 0x00,
460             0xFF, 0xFF, 0xFF, 0xFF };
461
462         /* This is an IPv4 address encapsulated in IPv6, so let's ignore it. */
463
464         if (memcmp(((struct sockaddr_in6*) sa)->sin6_addr.s6_addr, ipv4_in_ipv6, sizeof(ipv4_in_ipv6)) == 0)
465             return;
466     }
467
468     if (avahi_dns_packet_check_valid(p) < 0) {
469         g_warning("Recieved invalid packet.");
470         return;
471     }
472
473     port = avahi_port_from_sockaddr(sa);
474     avahi_address_from_sockaddr(sa, &a);
475
476     if (avahi_dns_packet_is_query(p)) {
477         gboolean legacy_unicast = FALSE;
478
479         if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT) == 0 ||
480             avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT) != 0) {
481             g_warning("Invalid query packet.");
482             return;
483         }
484
485         if (port != AVAHI_MDNS_PORT) {
486             /* Legacy Unicast */
487
488             if ((avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) != 0 ||
489                  avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0)) {
490                 g_warning("Invalid legacy unicast query packet.");
491                 return;
492             }
493         
494             legacy_unicast = TRUE;
495         }
496
497         handle_query(s, p, i, &a, port, legacy_unicast);
498         
499         g_message("Handled query");
500     } else {
501
502         if (port != AVAHI_MDNS_PORT) {
503             g_warning("Recieved repsonse with invalid source port %u on interface '%s.%i'", port, i->hardware->name, i->protocol);
504             return;
505         }
506
507         if (ttl != 255) {
508             g_warning("Recieved response with invalid TTL %u on interface '%s.%i'.", ttl, i->hardware->name, i->protocol);
509             if (!s->ignore_bad_ttl)
510                 return;
511         }
512
513         if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT) != 0 ||
514             avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) == 0 ||
515             avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0) {
516             g_warning("Invalid response packet.");
517             return;
518         }
519
520         handle_response(s, p, i, &a);
521         g_message("Handled response");
522     }
523 }
524
525 static void work(AvahiServer *s) {
526     struct sockaddr_in6 sa6;
527     struct sockaddr_in sa;
528     AvahiDnsPacket *p;
529     gint iface = -1;
530     guint8 ttl;
531         
532     g_assert(s);
533
534     if (s->pollfd_ipv4.revents & G_IO_IN) {
535         if ((p = avahi_recv_dns_packet_ipv4(s->fd_ipv4, &sa, &iface, &ttl))) {
536             dispatch_packet(s, p, (struct sockaddr*) &sa, iface, ttl);
537             avahi_dns_packet_free(p);
538         }
539     }
540
541     if (s->pollfd_ipv6.revents & G_IO_IN) {
542         if ((p = avahi_recv_dns_packet_ipv6(s->fd_ipv6, &sa6, &iface, &ttl))) {
543             dispatch_packet(s, p, (struct sockaddr*) &sa6, iface, ttl);
544             avahi_dns_packet_free(p);
545         }
546     }
547 }
548
549 static gboolean prepare_func(GSource *source, gint *timeout) {
550     g_assert(source);
551     g_assert(timeout);
552     
553     *timeout = -1;
554     return FALSE;
555 }
556
557 static gboolean check_func(GSource *source) {
558     AvahiServer* s;
559     g_assert(source);
560
561     s = *((AvahiServer**) (((guint8*) source) + sizeof(GSource)));
562     g_assert(s);
563     
564     return (s->pollfd_ipv4.revents | s->pollfd_ipv6.revents) & (G_IO_IN | G_IO_HUP | G_IO_ERR);
565 }
566
567 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
568     AvahiServer* s;
569     g_assert(source);
570
571     s = *((AvahiServer**) (((guint8*) source) + sizeof(GSource)));
572     g_assert(s);
573
574     work(s);
575     cleanup_dead(s);
576
577     return TRUE;
578 }
579
580 static void add_default_entries(AvahiServer *s) {
581     struct utsname utsname;
582     AvahiAddress a;
583     AvahiRecord *r;
584     
585     g_assert(s);
586     
587     /* Fill in HINFO rr */
588     r = avahi_record_new_full(s->hostname, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_HINFO);
589     uname(&utsname);
590     r->data.hinfo.cpu = g_strdup(g_strup(utsname.machine));
591     r->data.hinfo.os = g_strdup(g_strup(utsname.sysname));
592     avahi_server_add(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_UNIQUE, r);
593     avahi_record_unref(r);
594
595     /* Add localhost entries */
596     avahi_address_parse("127.0.0.1", AF_INET, &a);
597     avahi_server_add_address(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_UNIQUE|AVAHI_ENTRY_NOPROBE|AVAHI_ENTRY_NOANNOUNCE, "localhost", &a);
598
599     avahi_address_parse("::1", AF_INET6, &a);
600     avahi_server_add_address(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_UNIQUE|AVAHI_ENTRY_NOPROBE|AVAHI_ENTRY_NOANNOUNCE, "ip6-localhost", &a);
601 }
602
603 AvahiServer *avahi_server_new(GMainContext *c) {
604     gchar *hn;
605     AvahiServer *s;
606     
607     static GSourceFuncs source_funcs = {
608         prepare_func,
609         check_func,
610         dispatch_func,
611         NULL,
612         NULL,
613         NULL
614     };
615
616     s = g_new(AvahiServer, 1);
617
618     s->ignore_bad_ttl = FALSE;
619     s->need_entry_cleanup = s->need_group_cleanup = FALSE;
620     
621     s->fd_ipv4 = avahi_open_socket_ipv4();
622     s->fd_ipv6 = avahi_open_socket_ipv6();
623     
624     if (s->fd_ipv6 < 0 && s->fd_ipv4 < 0) {
625         g_critical("Failed to create IP sockets.\n");
626         g_free(s);
627         return NULL;
628     }
629
630     if (s->fd_ipv4 < 0)
631         g_message("Failed to create IPv4 socket, proceeding in IPv6 only mode");
632     else if (s->fd_ipv6 < 0)
633         g_message("Failed to create IPv6 socket, proceeding in IPv4 only mode");
634     
635     if (c)
636         g_main_context_ref(s->context = c);
637     else
638         s->context = g_main_context_default();
639     
640     AVAHI_LLIST_HEAD_INIT(AvahiEntry, s->entries);
641     s->entries_by_key = g_hash_table_new((GHashFunc) avahi_key_hash, (GEqualFunc) avahi_key_equal);
642     AVAHI_LLIST_HEAD_INIT(AvahiGroup, s->groups);
643
644     AVAHI_LLIST_HEAD_INIT(AvahiSubscription, s->subscriptions);
645     s->subscription_hashtable = g_hash_table_new((GHashFunc) avahi_key_hash, (GEqualFunc) avahi_key_equal);
646
647     /* Get host name */
648     hn = avahi_get_host_name();
649     hn[strcspn(hn, ".")] = 0;
650
651     s->hostname = g_strdup_printf("%s.local.", hn);
652     g_free(hn);
653
654     s->unicast_packet = NULL;
655
656     s->time_event_queue = avahi_time_event_queue_new(s->context, G_PRIORITY_DEFAULT+10); /* Slightly less priority than the FDs */
657     s->monitor = avahi_interface_monitor_new(s);
658     avahi_interface_monitor_sync(s->monitor);
659     add_default_entries(s);
660     
661     /* Prepare IO source registration */
662     s->source = g_source_new(&source_funcs, sizeof(GSource) + sizeof(AvahiServer*));
663     *((AvahiServer**) (((guint8*) s->source) + sizeof(GSource))) = s;
664
665     memset(&s->pollfd_ipv4, 0, sizeof(s->pollfd_ipv4));
666     s->pollfd_ipv4.fd = s->fd_ipv4;
667     s->pollfd_ipv4.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
668     g_source_add_poll(s->source, &s->pollfd_ipv4);
669     
670     memset(&s->pollfd_ipv6, 0, sizeof(s->pollfd_ipv6));
671     s->pollfd_ipv6.fd = s->fd_ipv6;
672     s->pollfd_ipv6.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
673     g_source_add_poll(s->source, &s->pollfd_ipv6);
674
675     g_source_attach(s->source, s->context);
676
677     return s;
678 }
679
680 void avahi_server_free(AvahiServer* s) {
681     g_assert(s);
682
683     while(s->entries)
684         free_entry(s, s->entries);
685
686     avahi_interface_monitor_free(s->monitor);
687
688     while (s->groups)
689         free_group(s, s->groups);
690
691     while (s->subscriptions)
692         avahi_subscription_free(s->subscriptions);
693     g_hash_table_destroy(s->subscription_hashtable);
694
695     g_hash_table_destroy(s->entries_by_key);
696
697     avahi_time_event_queue_free(s->time_event_queue);
698
699     if (s->fd_ipv4 >= 0)
700         close(s->fd_ipv4);
701     if (s->fd_ipv6 >= 0)
702         close(s->fd_ipv6);
703     
704     g_free(s->hostname);
705
706     g_source_destroy(s->source);
707     g_source_unref(s->source);
708     g_main_context_unref(s->context);
709
710     if (s->unicast_packet)
711         avahi_dns_packet_free(s->unicast_packet);
712
713     g_free(s);
714 }
715
716 void avahi_server_add(
717     AvahiServer *s,
718     AvahiEntryGroup *g,
719     gint interface,
720     guchar protocol,
721     AvahiEntryFlags flags,
722     AvahiRecord *r) {
723     
724     AvahiEntry *e, *t;
725     g_assert(s);
726     g_assert(r);
727
728     g_assert(r->key->type != AVAHI_DNS_TYPE_ANY);
729
730     e = g_new(AvahiEntry, 1);
731     e->server = s;
732     e->record = avahi_record_ref(r);
733     e->group = g;
734     e->interface = interface;
735     e->protocol = protocol;
736     e->flags = flags;
737     e->dead = FALSE;
738
739     AVAHI_LLIST_HEAD_INIT(AvahiAnnouncement, e->announcements);
740
741     AVAHI_LLIST_PREPEND(AvahiEntry, entries, s->entries, e);
742
743     /* Insert into hash table indexed by name */
744     t = g_hash_table_lookup(s->entries_by_key, e->record->key);
745     AVAHI_LLIST_PREPEND(AvahiEntry, by_key, t, e);
746     g_hash_table_replace(s->entries_by_key, e->record->key, t);
747
748     /* Insert into group list */
749     if (g)
750         AVAHI_LLIST_PREPEND(AvahiEntry, by_group, g->entries, e); 
751
752     avahi_announce_entry(s, e);
753 }
754 const AvahiRecord *avahi_server_iterate(AvahiServer *s, AvahiEntryGroup *g, void **state) {
755     AvahiEntry **e = (AvahiEntry**) state;
756     g_assert(s);
757     g_assert(e);
758
759     if (!*e)
760         *e = g ? g->entries : s->entries;
761     
762     while (*e && (*e)->dead)
763         *e = g ? (*e)->by_group_next : (*e)->entries_next;
764         
765     if (!*e)
766         return NULL;
767
768     return avahi_record_ref((*e)->record);
769 }
770
771 void avahi_server_dump(AvahiServer *s, FILE *f) {
772     AvahiEntry *e;
773     g_assert(s);
774     g_assert(f);
775
776     fprintf(f, "\n;;; ZONE DUMP FOLLOWS ;;;\n");
777
778     for (e = s->entries; e; e = e->entries_next) {
779         gchar *t;
780
781         if (e->dead)
782             continue;
783         
784         t = avahi_record_to_string(e->record);
785         fprintf(f, "%s ; iface=%i proto=%i\n", t, e->interface, e->protocol);
786         g_free(t);
787     }
788
789     avahi_dump_caches(s->monitor, f);
790 }
791
792 void avahi_server_add_ptr(
793     AvahiServer *s,
794     AvahiEntryGroup *g,
795     gint interface,
796     guchar protocol,
797     AvahiEntryFlags flags,
798     const gchar *name,
799     const gchar *dest) {
800
801     AvahiRecord *r;
802
803     g_assert(dest);
804
805     r = avahi_record_new_full(name ? name : s->hostname, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_PTR);
806     r->data.ptr.name = avahi_normalize_name(dest);
807     avahi_server_add(s, g, interface, protocol, flags, r);
808     avahi_record_unref(r);
809 }
810
811 void avahi_server_add_address(
812     AvahiServer *s,
813     AvahiEntryGroup *g,
814     gint interface,
815     guchar protocol,
816     AvahiEntryFlags flags,
817     const gchar *name,
818     AvahiAddress *a) {
819
820     gchar *n = NULL;
821     g_assert(s);
822     g_assert(a);
823
824     name = name ? (n = avahi_normalize_name(name)) : s->hostname;
825     
826     if (a->family == AF_INET) {
827         gchar *reverse;
828         AvahiRecord  *r;
829
830         r = avahi_record_new_full(name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_A);
831         r->data.a.address = a->data.ipv4;
832         avahi_server_add(s, g, interface, protocol, flags, r);
833         avahi_record_unref(r);
834         
835         reverse = avahi_reverse_lookup_name_ipv4(&a->data.ipv4);
836         g_assert(reverse);
837         avahi_server_add_ptr(s, g, interface, protocol, flags, reverse, name);
838         g_free(reverse);
839         
840     } else {
841         gchar *reverse;
842         AvahiRecord *r;
843             
844         r = avahi_record_new_full(name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_AAAA);
845         r->data.aaaa.address = a->data.ipv6;
846         avahi_server_add(s, g, interface, protocol, flags, r);
847         avahi_record_unref(r);
848
849         reverse = avahi_reverse_lookup_name_ipv6_arpa(&a->data.ipv6);
850         g_assert(reverse);
851         avahi_server_add_ptr(s, g, interface, protocol, flags, reverse, name);
852         g_free(reverse);
853     
854         reverse = avahi_reverse_lookup_name_ipv6_int(&a->data.ipv6);
855         g_assert(reverse);
856         avahi_server_add_ptr(s, g, interface, protocol, flags, reverse, name);
857         g_free(reverse);
858     }
859     
860     g_free(n);
861 }
862
863 void avahi_server_add_text_strlst(
864     AvahiServer *s,
865     AvahiEntryGroup *g,
866     gint interface,
867     guchar protocol,
868     AvahiEntryFlags flags,
869     const gchar *name,
870     AvahiStringList *strlst) {
871
872     AvahiRecord *r;
873     
874     g_assert(s);
875     
876     r = avahi_record_new_full(name ? name : s->hostname, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_TXT);
877     r->data.txt.string_list = strlst;
878     avahi_server_add(s, g, interface, protocol, flags, r);
879     avahi_record_unref(r);
880 }
881
882 void avahi_server_add_text_va(
883     AvahiServer *s,
884     AvahiEntryGroup *g,
885     gint interface,
886     guchar protocol,
887     AvahiEntryFlags flags,
888     const gchar *name,
889     va_list va) {
890     
891     g_assert(s);
892
893     avahi_server_add_text_strlst(s, g, interface, protocol, flags, name, avahi_string_list_new_va(va));
894 }
895
896 void avahi_server_add_text(
897     AvahiServer *s,
898     AvahiEntryGroup *g,
899     gint interface,
900     guchar protocol,
901     AvahiEntryFlags flags,
902     const gchar *name,
903     ...) {
904
905     va_list va;
906     
907     g_assert(s);
908
909     va_start(va, name);
910     avahi_server_add_text_va(s, g, interface, protocol, flags, name, va);
911     va_end(va);
912 }
913
914 static void escape_service_name(gchar *d, guint size, const gchar *s) {
915     g_assert(d);
916     g_assert(size);
917     g_assert(s);
918
919     while (*s && size >= 2) {
920         if (*s == '.' || *s == '\\') {
921             if (size < 3)
922                 break;
923
924             *(d++) = '\\';
925             size--;
926         }
927             
928         *(d++) = *(s++);
929         size--;
930     }
931
932     g_assert(size > 0);
933     *(d++) = 0;
934 }
935
936 void avahi_server_add_service_strlst(
937     AvahiServer *s,
938     AvahiEntryGroup *g,
939     gint interface,
940     guchar protocol,
941     const gchar *type,
942     const gchar *name,
943     const gchar *domain,
944     const gchar *host,
945     guint16 port,
946     AvahiStringList *strlst) {
947
948     gchar ptr_name[256], svc_name[256], ename[64], enum_ptr[256];
949     AvahiRecord *r;
950     
951     g_assert(s);
952     g_assert(type);
953     g_assert(name);
954
955     escape_service_name(ename, sizeof(ename), name);
956
957     if (domain) {
958         while (domain[0] == '.')
959             domain++;
960     } else
961         domain = "local";
962
963     if (!host)
964         host = s->hostname;
965
966     snprintf(ptr_name, sizeof(ptr_name), "%s.%s", type, domain);
967     snprintf(svc_name, sizeof(svc_name), "%s.%s.%s", ename, type, domain);
968     
969     avahi_server_add_ptr(s, g, interface, protocol, AVAHI_ENTRY_NULL, ptr_name, svc_name);
970
971     r = avahi_record_new_full(svc_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_SRV);
972     r->data.srv.priority = 0;
973     r->data.srv.weight = 0;
974     r->data.srv.port = port;
975     r->data.srv.name = avahi_normalize_name(host);
976     avahi_server_add(s, g, interface, protocol, AVAHI_ENTRY_UNIQUE, r);
977     avahi_record_unref(r);
978
979     avahi_server_add_text_strlst(s, g, interface, protocol, AVAHI_ENTRY_UNIQUE, svc_name, strlst);
980
981     snprintf(enum_ptr, sizeof(enum_ptr), "_services._dns-sd._udp.%s", domain);
982     avahi_server_add_ptr(s, g, interface, protocol, AVAHI_ENTRY_NULL, enum_ptr, ptr_name);
983 }
984
985 void avahi_server_add_service_va(
986     AvahiServer *s,
987     AvahiEntryGroup *g,
988     gint interface,
989     guchar protocol,
990     const gchar *type,
991     const gchar *name,
992     const gchar *domain,
993     const gchar *host,
994     guint16 port,
995     va_list va){
996
997     g_assert(s);
998     g_assert(type);
999     g_assert(name);
1000
1001     avahi_server_add_service(s, g, interface, protocol, type, name, domain, host, port, avahi_string_list_new_va(va));
1002 }
1003
1004 void avahi_server_add_service(
1005     AvahiServer *s,
1006     AvahiEntryGroup *g,
1007     gint interface,
1008     guchar protocol,
1009     const gchar *type,
1010     const gchar *name,
1011     const gchar *domain,
1012     const gchar *host,
1013     guint16 port,
1014     ... ){
1015
1016     va_list va;
1017     
1018     g_assert(s);
1019     g_assert(type);
1020     g_assert(name);
1021
1022     va_start(va, port);
1023     avahi_server_add_service_va(s, g, interface, protocol, type, name, domain, host, port, va);
1024     va_end(va);
1025 }
1026
1027 static void post_query_callback(AvahiInterfaceMonitor *m, AvahiInterface *i, gpointer userdata) {
1028     AvahiKey *k = userdata;
1029
1030     g_assert(m);
1031     g_assert(i);
1032     g_assert(k);
1033
1034     avahi_interface_post_query(i, k, FALSE);
1035 }
1036
1037 void avahi_server_post_query(AvahiServer *s, gint interface, guchar protocol, AvahiKey *key) {
1038     g_assert(s);
1039     g_assert(key);
1040
1041     avahi_interface_monitor_walk(s->monitor, interface, protocol, post_query_callback, key);
1042 }
1043
1044 struct tmpdata {
1045     AvahiRecord *record;
1046     gboolean flush_cache;
1047 };
1048
1049 static void post_response_callback(AvahiInterfaceMonitor *m, AvahiInterface *i, gpointer userdata) {
1050     struct tmpdata *tmpdata = userdata;
1051
1052     g_assert(m);
1053     g_assert(i);
1054     g_assert(tmpdata);
1055
1056     avahi_interface_post_response(i, NULL, tmpdata->record, tmpdata->flush_cache, FALSE);
1057 }
1058
1059 void avahi_server_post_response(AvahiServer *s, gint interface, guchar protocol, AvahiRecord *record, gboolean flush_cache) {
1060     struct tmpdata tmpdata;
1061     
1062     g_assert(s);
1063     g_assert(record);
1064
1065     tmpdata.record = record;
1066     tmpdata.flush_cache = flush_cache;
1067
1068     avahi_interface_monitor_walk(s->monitor, interface, protocol, post_response_callback, &tmpdata);
1069 }
1070
1071 void avahi_entry_group_change_state(AvahiEntryGroup *g, AvahiEntryGroupState state) {
1072     g_assert(g);
1073
1074     g->state = state;
1075     
1076     if (g->callback) {
1077         g->callback(g->server, g, state, g->userdata);
1078         return;
1079     }
1080 }
1081
1082 AvahiEntryGroup *avahi_entry_group_new(AvahiServer *s, AvahiEntryGroupCallback callback, gpointer userdata) {
1083     AvahiEntryGroup *g;
1084     
1085     g_assert(s);
1086
1087     g = g_new(AvahiEntryGroup, 1);
1088     g->server = s;
1089     g->callback = callback;
1090     g->userdata = userdata;
1091     g->dead = FALSE;
1092     g->state = AVAHI_ENTRY_GROUP_UNCOMMITED;
1093     g->n_probing = 0;
1094     AVAHI_LLIST_HEAD_INIT(AvahiEntry, g->entries);
1095
1096     AVAHI_LLIST_PREPEND(AvahiEntryGroup, groups, s->groups, g);
1097     return g;
1098 }
1099
1100 void avahi_entry_group_free(AvahiEntryGroup *g) {
1101     g_assert(g);
1102     g_assert(g->server);
1103
1104     g->dead = TRUE;
1105     g->server->need_group_cleanup = TRUE;
1106 }
1107
1108 void avahi_entry_group_commit(AvahiEntryGroup *g) {
1109     g_assert(g);
1110     g_assert(!g->dead);
1111
1112     if (g->state != AVAHI_ENTRY_GROUP_UNCOMMITED)
1113         return;
1114
1115     avahi_entry_group_change_state(g, AVAHI_ENTRY_GROUP_REGISTERING);
1116     avahi_announce_group(g->server, g);
1117     avahi_entry_group_check_probed(g, FALSE);
1118 }
1119
1120 gboolean avahi_entry_commited(AvahiEntry *e) {
1121     g_assert(e);
1122     g_assert(!e->dead);
1123
1124     return !e->group ||
1125         e->group->state == AVAHI_ENTRY_GROUP_REGISTERING ||
1126         e->group->state == AVAHI_ENTRY_GROUP_ESTABLISHED;
1127 }
1128
1129 AvahiEntryGroupState avahi_entry_group_get_state(AvahiEntryGroup *g) {
1130     g_assert(g);
1131     g_assert(!g->dead);
1132
1133     return g->state;
1134 }