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