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