]> git.meshlink.io Git - catta/blob - avahi-core/server.c
* case insensitive name comparisons
[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             avahi_record_list_flush(s->record_list);
420             return;
421        }
422
423         avahi_packet_scheduler_incoming_query(i->scheduler, key);
424         avahi_server_prepare_matching_responses(s, i, key, unicast_response);
425         avahi_key_unref(key);
426     }
427
428     if (!avahi_record_list_empty(s->record_list))
429         avahi_server_generate_response(s, i, p, a, port, legacy_unicast);
430     
431     /* Known Answer Suppression */
432     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT); n > 0; n --) {
433         AvahiRecord *record;
434         gboolean unique = FALSE;
435
436         if (!(record = avahi_dns_packet_consume_record(p, &unique))) {
437             g_warning("Packet too short (2)");
438             return;
439         }
440
441         if (handle_conflict(s, i, record, unique, a))
442             avahi_packet_scheduler_incoming_known_answer(i->scheduler, record, a);
443         
444         avahi_record_unref(record);
445     }
446
447     /* Probe record */
448     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT); n > 0; n --) {
449         AvahiRecord *record;
450         gboolean unique = FALSE;
451
452         if (!(record = avahi_dns_packet_consume_record(p, &unique))) {
453             g_warning("Packet too short (3)");
454             return;
455         }
456
457         if (record->key->type != AVAHI_DNS_TYPE_ANY)
458             incoming_probe(s, record, i);
459         
460         avahi_record_unref(record);
461     }
462 }
463
464 static void handle_response(AvahiServer *s, AvahiDnsPacket *p, AvahiInterface *i, const AvahiAddress *a) {
465     guint n;
466     
467     g_assert(s);
468     g_assert(p);
469     g_assert(i);
470     g_assert(a);
471
472 /*     g_message("response"); */
473     
474     for (n = avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) +
475              avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT); n > 0; n--) {
476         AvahiRecord *record;
477         gboolean cache_flush = FALSE;
478         gchar *txt;
479         
480         if (!(record = avahi_dns_packet_consume_record(p, &cache_flush))) {
481             g_warning("Packet too short (4)");
482             break;
483         }
484
485         if (record->key->type != AVAHI_DNS_TYPE_ANY) {
486
487             g_message("Handling response: %s", txt = avahi_record_to_string(record));
488             g_free(txt);
489             
490             if (handle_conflict(s, i, record, cache_flush, a)) {
491                 avahi_cache_update(i->cache, record, cache_flush, a);
492                 avahi_packet_scheduler_incoming_response(i->scheduler, record, cache_flush);
493             }
494         }
495             
496         avahi_record_unref(record);
497     }
498 }
499
500 static void dispatch_packet(AvahiServer *s, AvahiDnsPacket *p, struct sockaddr *sa, gint iface, gint ttl) {
501     AvahiInterface *i;
502     AvahiAddress a;
503     guint16 port;
504     
505     g_assert(s);
506     g_assert(p);
507     g_assert(sa);
508     g_assert(iface > 0);
509
510     if (!(i = avahi_interface_monitor_get_interface(s->monitor, iface, sa->sa_family)) ||
511         !avahi_interface_relevant(i)) {
512         g_warning("Recieved packet from invalid interface.");
513         return;
514     }
515
516     g_message("new packet recieved on interface '%s.%i'.", i->hardware->name, i->protocol);
517
518     if (sa->sa_family == AF_INET6) {
519         static const guint8 ipv4_in_ipv6[] = {
520             0x00, 0x00, 0x00, 0x00,
521             0x00, 0x00, 0x00, 0x00,
522             0xFF, 0xFF, 0xFF, 0xFF };
523
524         /* This is an IPv4 address encapsulated in IPv6, so let's ignore it. */
525
526         if (memcmp(((struct sockaddr_in6*) sa)->sin6_addr.s6_addr, ipv4_in_ipv6, sizeof(ipv4_in_ipv6)) == 0)
527             return;
528     }
529
530     if (avahi_dns_packet_check_valid(p) < 0) {
531         g_warning("Recieved invalid packet.");
532         return;
533     }
534
535     port = avahi_port_from_sockaddr(sa);
536     avahi_address_from_sockaddr(sa, &a);
537
538     if (avahi_dns_packet_is_query(p)) {
539         gboolean legacy_unicast = FALSE;
540
541         if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT) != 0) {
542             g_warning("Invalid query packet.");
543             return;
544         }
545
546         if (port != AVAHI_MDNS_PORT) {
547             /* Legacy Unicast */
548
549             if ((avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) != 0 ||
550                  avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0)) {
551                 g_warning("Invalid legacy unicast query packet.");
552                 return;
553             }
554         
555             legacy_unicast = TRUE;
556         }
557
558         handle_query(s, p, i, &a, port, legacy_unicast);
559         
560         g_message("Handled query");
561     } else {
562
563         if (port != AVAHI_MDNS_PORT) {
564             g_warning("Recieved repsonse with invalid source port %u on interface '%s.%i'", port, i->hardware->name, i->protocol);
565             return;
566         }
567
568         if (ttl != 255) {
569             g_warning("Recieved response with invalid TTL %u on interface '%s.%i'.", ttl, i->hardware->name, i->protocol);
570             if (!s->ignore_bad_ttl)
571                 return;
572         }
573
574         if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT) != 0 ||
575             avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) == 0 ||
576             avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0) {
577             g_warning("Invalid response packet.");
578             return;
579         }
580
581         handle_response(s, p, i, &a);
582         g_message("Handled response");
583     }
584 }
585
586 static void work(AvahiServer *s) {
587     struct sockaddr_in6 sa6;
588     struct sockaddr_in sa;
589     AvahiDnsPacket *p;
590     gint iface = -1;
591     guint8 ttl;
592         
593     g_assert(s);
594
595     if (s->pollfd_ipv4.revents & G_IO_IN) {
596         if ((p = avahi_recv_dns_packet_ipv4(s->fd_ipv4, &sa, &iface, &ttl))) {
597             dispatch_packet(s, p, (struct sockaddr*) &sa, iface, ttl);
598             avahi_dns_packet_free(p);
599         }
600     }
601
602     if (s->pollfd_ipv6.revents & G_IO_IN) {
603         if ((p = avahi_recv_dns_packet_ipv6(s->fd_ipv6, &sa6, &iface, &ttl))) {
604             dispatch_packet(s, p, (struct sockaddr*) &sa6, iface, ttl);
605             avahi_dns_packet_free(p);
606         }
607     }
608 }
609
610 static gboolean prepare_func(GSource *source, gint *timeout) {
611     g_assert(source);
612     g_assert(timeout);
613     
614     *timeout = -1;
615     return FALSE;
616 }
617
618 static gboolean check_func(GSource *source) {
619     AvahiServer* s;
620     g_assert(source);
621
622     s = *((AvahiServer**) (((guint8*) source) + sizeof(GSource)));
623     g_assert(s);
624     
625     return (s->pollfd_ipv4.revents | s->pollfd_ipv6.revents) & (G_IO_IN | G_IO_HUP | G_IO_ERR);
626 }
627
628 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
629     AvahiServer* s;
630     g_assert(source);
631
632     s = *((AvahiServer**) (((guint8*) source) + sizeof(GSource)));
633     g_assert(s);
634
635     work(s);
636     cleanup_dead(s);
637
638     return TRUE;
639 }
640
641 static void add_default_entries(AvahiServer *s) {
642     struct utsname utsname;
643     AvahiAddress a;
644     AvahiRecord *r;
645     
646     g_assert(s);
647
648     return ;
649     
650     /* Fill in HINFO rr */
651     r = avahi_record_new_full(s->host_name_fqdn, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_HINFO);
652     uname(&utsname);
653     r->data.hinfo.cpu = g_strdup(g_strup(utsname.machine));
654     r->data.hinfo.os = g_strdup(g_strup(utsname.sysname));
655     avahi_server_add(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_UNIQUE, r);
656     avahi_record_unref(r);
657
658     /* Add localhost entries */
659     avahi_address_parse("127.0.0.1", AF_INET, &a);
660     avahi_server_add_address(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_NOPROBE|AVAHI_ENTRY_NOANNOUNCE, "localhost", &a);
661
662     avahi_address_parse("::1", AF_INET6, &a);
663     avahi_server_add_address(s, NULL, 0, AF_UNSPEC, AVAHI_ENTRY_NOPROBE|AVAHI_ENTRY_NOANNOUNCE, "ip6-localhost", &a);
664 }
665
666 AvahiServer *avahi_server_new(GMainContext *c) {
667     AvahiServer *s;
668     
669     static GSourceFuncs source_funcs = {
670         prepare_func,
671         check_func,
672         dispatch_func,
673         NULL,
674         NULL,
675         NULL
676     };
677
678     s = g_new(AvahiServer, 1);
679
680     s->ignore_bad_ttl = FALSE;
681     s->need_entry_cleanup = s->need_group_cleanup = FALSE;
682     
683     s->fd_ipv4 = avahi_open_socket_ipv4();
684     s->fd_ipv6 = -1 /* avahi_open_socket_ipv6() */ ;
685     
686     if (s->fd_ipv6 < 0 && s->fd_ipv4 < 0) {
687         g_critical("Failed to create IP sockets.\n");
688         g_free(s);
689         return NULL;
690     }
691
692     if (s->fd_ipv4 < 0)
693         g_message("Failed to create IPv4 socket, proceeding in IPv6 only mode");
694     else if (s->fd_ipv6 < 0)
695         g_message("Failed to create IPv6 socket, proceeding in IPv4 only mode");
696     
697     if (c)
698         g_main_context_ref(s->context = c);
699     else
700         s->context = g_main_context_default();
701     
702     AVAHI_LLIST_HEAD_INIT(AvahiEntry, s->entries);
703     s->entries_by_key = g_hash_table_new((GHashFunc) avahi_key_hash, (GEqualFunc) avahi_key_equal);
704     AVAHI_LLIST_HEAD_INIT(AvahiGroup, s->groups);
705
706     AVAHI_LLIST_HEAD_INIT(AvahiSubscription, s->subscriptions);
707     s->subscription_hashtable = g_hash_table_new((GHashFunc) avahi_key_hash, (GEqualFunc) avahi_key_equal);
708
709     /* Get host name */
710     s->host_name = avahi_get_host_name();
711     s->host_name[strcspn(s->host_name, ".")] = 0;
712
713     s->domain = avahi_normalize_name("local.");
714
715     s->host_name_fqdn = g_strdup_printf("%s.%s", s->host_name, s->domain);
716
717     s->record_list = avahi_record_list_new();
718
719     s->time_event_queue = avahi_time_event_queue_new(s->context, G_PRIORITY_DEFAULT+10); /* Slightly less priority than the FDs */
720     s->monitor = avahi_interface_monitor_new(s);
721     avahi_interface_monitor_sync(s->monitor);
722     add_default_entries(s);
723     
724     /* Prepare IO source registration */
725     s->source = g_source_new(&source_funcs, sizeof(GSource) + sizeof(AvahiServer*));
726     *((AvahiServer**) (((guint8*) s->source) + sizeof(GSource))) = s;
727
728     memset(&s->pollfd_ipv4, 0, sizeof(s->pollfd_ipv4));
729     s->pollfd_ipv4.fd = s->fd_ipv4;
730     s->pollfd_ipv4.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
731     g_source_add_poll(s->source, &s->pollfd_ipv4);
732     
733     memset(&s->pollfd_ipv6, 0, sizeof(s->pollfd_ipv6));
734     s->pollfd_ipv6.fd = s->fd_ipv6;
735     s->pollfd_ipv6.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
736     g_source_add_poll(s->source, &s->pollfd_ipv6);
737
738     g_source_attach(s->source, s->context);
739
740     return s;
741 }
742
743 void avahi_server_free(AvahiServer* s) {
744     g_assert(s);
745
746     while(s->entries)
747         free_entry(s, s->entries);
748
749     avahi_interface_monitor_free(s->monitor);
750
751     while (s->groups)
752         free_group(s, s->groups);
753
754     while (s->subscriptions)
755         avahi_subscription_free(s->subscriptions);
756     g_hash_table_destroy(s->subscription_hashtable);
757
758     g_hash_table_destroy(s->entries_by_key);
759
760     avahi_time_event_queue_free(s->time_event_queue);
761
762     avahi_record_list_free(s->record_list);
763     
764     if (s->fd_ipv4 >= 0)
765         close(s->fd_ipv4);
766     if (s->fd_ipv6 >= 0)
767         close(s->fd_ipv6);
768
769     g_free(s->host_name);
770     g_free(s->domain);
771     g_free(s->host_name_fqdn);
772
773     g_source_destroy(s->source);
774     g_source_unref(s->source);
775     g_main_context_unref(s->context);
776
777     g_free(s);
778 }
779
780 void avahi_server_add(
781     AvahiServer *s,
782     AvahiEntryGroup *g,
783     gint interface,
784     guchar protocol,
785     AvahiEntryFlags flags,
786     AvahiRecord *r) {
787     
788     AvahiEntry *e, *t;
789     g_assert(s);
790     g_assert(r);
791
792     g_assert(r->key->type != AVAHI_DNS_TYPE_ANY);
793
794     e = g_new(AvahiEntry, 1);
795     e->server = s;
796     e->record = avahi_record_ref(r);
797     e->group = g;
798     e->interface = interface;
799     e->protocol = protocol;
800     e->flags = flags;
801     e->dead = FALSE;
802
803     AVAHI_LLIST_HEAD_INIT(AvahiAnnouncement, e->announcements);
804
805     AVAHI_LLIST_PREPEND(AvahiEntry, entries, s->entries, e);
806
807     /* Insert into hash table indexed by name */
808     t = g_hash_table_lookup(s->entries_by_key, e->record->key);
809     AVAHI_LLIST_PREPEND(AvahiEntry, by_key, t, e);
810     g_hash_table_replace(s->entries_by_key, e->record->key, t);
811
812     /* Insert into group list */
813     if (g)
814         AVAHI_LLIST_PREPEND(AvahiEntry, by_group, g->entries, e); 
815
816     avahi_announce_entry(s, e);
817 }
818 const AvahiRecord *avahi_server_iterate(AvahiServer *s, AvahiEntryGroup *g, void **state) {
819     AvahiEntry **e = (AvahiEntry**) state;
820     g_assert(s);
821     g_assert(e);
822
823     if (!*e)
824         *e = g ? g->entries : s->entries;
825     
826     while (*e && (*e)->dead)
827         *e = g ? (*e)->by_group_next : (*e)->entries_next;
828         
829     if (!*e)
830         return NULL;
831
832     return avahi_record_ref((*e)->record);
833 }
834
835 void avahi_server_dump(AvahiServer *s, FILE *f) {
836     AvahiEntry *e;
837     g_assert(s);
838     g_assert(f);
839
840     fprintf(f, "\n;;; ZONE DUMP FOLLOWS ;;;\n");
841
842     for (e = s->entries; e; e = e->entries_next) {
843         gchar *t;
844
845         if (e->dead)
846             continue;
847         
848         t = avahi_record_to_string(e->record);
849         fprintf(f, "%s ; iface=%i proto=%i\n", t, e->interface, e->protocol);
850         g_free(t);
851     }
852
853     avahi_dump_caches(s->monitor, f);
854 }
855
856 void avahi_server_add_ptr(
857     AvahiServer *s,
858     AvahiEntryGroup *g,
859     gint interface,
860     guchar protocol,
861     AvahiEntryFlags flags,
862     const gchar *name,
863     const gchar *dest) {
864
865     AvahiRecord *r;
866
867     g_assert(dest);
868
869     r = avahi_record_new_full(name ? name : s->host_name_fqdn, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_PTR);
870     r->data.ptr.name = avahi_normalize_name(dest);
871     avahi_server_add(s, g, interface, protocol, flags, r);
872     avahi_record_unref(r);
873 }
874
875 void avahi_server_add_address(
876     AvahiServer *s,
877     AvahiEntryGroup *g,
878     gint interface,
879     guchar protocol,
880     AvahiEntryFlags flags,
881     const gchar *name,
882     AvahiAddress *a) {
883
884     gchar *n = NULL;
885     g_assert(s);
886     g_assert(a);
887
888     name = name ? (n = avahi_normalize_name(name)) : s->host_name_fqdn;
889     
890     if (a->family == AF_INET) {
891         gchar *reverse;
892         AvahiRecord  *r;
893
894         r = avahi_record_new_full(name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_A);
895         r->data.a.address = a->data.ipv4;
896         avahi_server_add(s, g, interface, protocol, flags | AVAHI_ENTRY_UNIQUE, r);
897         avahi_record_unref(r);
898         
899         reverse = avahi_reverse_lookup_name_ipv4(&a->data.ipv4);
900         avahi_server_add_ptr(s, g, interface, protocol, flags | AVAHI_ENTRY_UNIQUE, reverse, name);
901         g_free(reverse);
902         
903     } else {
904         gchar *reverse;
905         AvahiRecord *r;
906             
907         r = avahi_record_new_full(name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_AAAA);
908         r->data.aaaa.address = a->data.ipv6;
909         avahi_server_add(s, g, interface, protocol, flags | AVAHI_ENTRY_UNIQUE, r);
910         avahi_record_unref(r);
911
912         reverse = avahi_reverse_lookup_name_ipv6_arpa(&a->data.ipv6);
913         avahi_server_add_ptr(s, g, interface, protocol, flags | AVAHI_ENTRY_UNIQUE, reverse, name);
914         g_free(reverse);
915     
916         reverse = avahi_reverse_lookup_name_ipv6_int(&a->data.ipv6);
917         avahi_server_add_ptr(s, g, interface, protocol, flags | AVAHI_ENTRY_UNIQUE, reverse, name);
918         g_free(reverse);
919     }
920     
921     g_free(n);
922 }
923
924 void avahi_server_add_text_strlst(
925     AvahiServer *s,
926     AvahiEntryGroup *g,
927     gint interface,
928     guchar protocol,
929     AvahiEntryFlags flags,
930     const gchar *name,
931     AvahiStringList *strlst) {
932
933     AvahiRecord *r;
934     
935     g_assert(s);
936     
937     r = avahi_record_new_full(name ? name : s->host_name_fqdn, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_TXT);
938     r->data.txt.string_list = strlst;
939     avahi_server_add(s, g, interface, protocol, flags, r);
940     avahi_record_unref(r);
941 }
942
943 void avahi_server_add_text_va(
944     AvahiServer *s,
945     AvahiEntryGroup *g,
946     gint interface,
947     guchar protocol,
948     AvahiEntryFlags flags,
949     const gchar *name,
950     va_list va) {
951     
952     g_assert(s);
953
954     avahi_server_add_text_strlst(s, g, interface, protocol, flags, name, avahi_string_list_new_va(va));
955 }
956
957 void avahi_server_add_text(
958     AvahiServer *s,
959     AvahiEntryGroup *g,
960     gint interface,
961     guchar protocol,
962     AvahiEntryFlags flags,
963     const gchar *name,
964     ...) {
965
966     va_list va;
967     
968     g_assert(s);
969
970     va_start(va, name);
971     avahi_server_add_text_va(s, g, interface, protocol, flags, name, va);
972     va_end(va);
973 }
974
975 static void escape_service_name(gchar *d, guint size, const gchar *s) {
976     g_assert(d);
977     g_assert(size);
978     g_assert(s);
979
980     while (*s && size >= 2) {
981         if (*s == '.' || *s == '\\') {
982             if (size < 3)
983                 break;
984
985             *(d++) = '\\';
986             size--;
987         }
988             
989         *(d++) = *(s++);
990         size--;
991     }
992
993     g_assert(size > 0);
994     *(d++) = 0;
995 }
996
997 void avahi_server_add_service_strlst(
998     AvahiServer *s,
999     AvahiEntryGroup *g,
1000     gint interface,
1001     guchar protocol,
1002     const gchar *type,
1003     const gchar *name,
1004     const gchar *domain,
1005     const gchar *host,
1006     guint16 port,
1007     AvahiStringList *strlst) {
1008
1009     gchar ptr_name[256], svc_name[256], ename[64], enum_ptr[256];
1010     AvahiRecord *r;
1011     
1012     g_assert(s);
1013     g_assert(type);
1014     g_assert(name);
1015
1016     escape_service_name(ename, sizeof(ename), name);
1017
1018     if (domain) {
1019         while (domain[0] == '.')
1020             domain++;
1021     } else
1022         domain = "local";
1023
1024     if (!host)
1025         host = s->host_name_fqdn;
1026
1027     snprintf(ptr_name, sizeof(ptr_name), "%s.%s", type, domain);
1028     snprintf(svc_name, sizeof(svc_name), "%s.%s.%s", ename, type, domain);
1029     
1030     avahi_server_add_ptr(s, g, interface, protocol, AVAHI_ENTRY_NULL, ptr_name, svc_name);
1031
1032     r = avahi_record_new_full(svc_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_SRV);
1033     r->data.srv.priority = 0;
1034     r->data.srv.weight = 0;
1035     r->data.srv.port = port;
1036     r->data.srv.name = avahi_normalize_name(host);
1037     avahi_server_add(s, g, interface, protocol, AVAHI_ENTRY_UNIQUE, r);
1038     avahi_record_unref(r);
1039
1040     avahi_server_add_text_strlst(s, g, interface, protocol, AVAHI_ENTRY_UNIQUE, svc_name, strlst);
1041
1042     snprintf(enum_ptr, sizeof(enum_ptr), "_services._dns-sd._udp.%s", domain);
1043     avahi_server_add_ptr(s, g, interface, protocol, AVAHI_ENTRY_NULL, enum_ptr, ptr_name);
1044 }
1045
1046 void avahi_server_add_service_va(
1047     AvahiServer *s,
1048     AvahiEntryGroup *g,
1049     gint interface,
1050     guchar protocol,
1051     const gchar *type,
1052     const gchar *name,
1053     const gchar *domain,
1054     const gchar *host,
1055     guint16 port,
1056     va_list va){
1057
1058     g_assert(s);
1059     g_assert(type);
1060     g_assert(name);
1061
1062     avahi_server_add_service_strlst(s, g, interface, protocol, type, name, domain, host, port, avahi_string_list_new_va(va));
1063 }
1064
1065 void avahi_server_add_service(
1066     AvahiServer *s,
1067     AvahiEntryGroup *g,
1068     gint interface,
1069     guchar protocol,
1070     const gchar *type,
1071     const gchar *name,
1072     const gchar *domain,
1073     const gchar *host,
1074     guint16 port,
1075     ... ){
1076
1077     va_list va;
1078     
1079     g_assert(s);
1080     g_assert(type);
1081     g_assert(name);
1082
1083     va_start(va, port);
1084     avahi_server_add_service_va(s, g, interface, protocol, type, name, domain, host, port, va);
1085     va_end(va);
1086 }
1087
1088 static void post_query_callback(AvahiInterfaceMonitor *m, AvahiInterface *i, gpointer userdata) {
1089     AvahiKey *k = userdata;
1090
1091     g_assert(m);
1092     g_assert(i);
1093     g_assert(k);
1094
1095     avahi_interface_post_query(i, k, FALSE);
1096 }
1097
1098 void avahi_server_post_query(AvahiServer *s, gint interface, guchar protocol, AvahiKey *key) {
1099     g_assert(s);
1100     g_assert(key);
1101
1102     avahi_interface_monitor_walk(s->monitor, interface, protocol, post_query_callback, key);
1103 }
1104
1105 void avahi_entry_group_change_state(AvahiEntryGroup *g, AvahiEntryGroupState state) {
1106     g_assert(g);
1107
1108     if (g->state == state)
1109         return;
1110     
1111     g->state = state;
1112     
1113     if (g->callback) {
1114         g->callback(g->server, g, state, g->userdata);
1115         return;
1116     }
1117 }
1118
1119 AvahiEntryGroup *avahi_entry_group_new(AvahiServer *s, AvahiEntryGroupCallback callback, gpointer userdata) {
1120     AvahiEntryGroup *g;
1121     
1122     g_assert(s);
1123
1124     g = g_new(AvahiEntryGroup, 1);
1125     g->server = s;
1126     g->callback = callback;
1127     g->userdata = userdata;
1128     g->dead = FALSE;
1129     g->state = AVAHI_ENTRY_GROUP_UNCOMMITED;
1130     g->n_probing = 0;
1131     AVAHI_LLIST_HEAD_INIT(AvahiEntry, g->entries);
1132
1133     AVAHI_LLIST_PREPEND(AvahiEntryGroup, groups, s->groups, g);
1134     return g;
1135 }
1136
1137 void avahi_entry_group_free(AvahiEntryGroup *g) {
1138     g_assert(g);
1139     g_assert(g->server);
1140
1141     g->dead = TRUE;
1142     g->server->need_group_cleanup = TRUE;
1143 }
1144
1145 void avahi_entry_group_commit(AvahiEntryGroup *g) {
1146     g_assert(g);
1147     g_assert(!g->dead);
1148
1149     if (g->state != AVAHI_ENTRY_GROUP_UNCOMMITED)
1150         return;
1151
1152     avahi_entry_group_change_state(g, AVAHI_ENTRY_GROUP_REGISTERING);
1153     avahi_announce_group(g->server, g);
1154     avahi_entry_group_check_probed(g, FALSE);
1155 }
1156
1157 gboolean avahi_entry_commited(AvahiEntry *e) {
1158     g_assert(e);
1159     g_assert(!e->dead);
1160
1161     return !e->group ||
1162         e->group->state == AVAHI_ENTRY_GROUP_REGISTERING ||
1163         e->group->state == AVAHI_ENTRY_GROUP_ESTABLISHED;
1164 }
1165
1166 AvahiEntryGroupState avahi_entry_group_get_state(AvahiEntryGroup *g) {
1167     g_assert(g);
1168     g_assert(!g->dead);
1169
1170     return g->state;
1171 }
1172
1173 const gchar* avahi_server_get_domain(AvahiServer *s) {
1174     g_assert(s);
1175
1176     return s->domain;
1177 }
1178
1179 const gchar* avahi_server_get_host_name(AvahiServer *s) {
1180     g_assert(s);
1181
1182     return s->host_name_fqdn;
1183 }