]> git.meshlink.io Git - catta/blob - server.c
fcf42487d9a85dfb9aef65c2306a345636e53e3b
[catta] / server.c
1 #include <sys/socket.h>
2 #include <arpa/inet.h>
3 #include <string.h>
4 #include <sys/utsname.h>
5 #include <unistd.h>
6
7 #include "server.h"
8 #include "util.h"
9 #include "iface.h"
10 #include "socket.h"
11 #include "subscribe.h"
12
13 static void handle_query_key(flxServer *s, flxKey *k, flxInterface *i, const flxAddress *a) {
14     flxServerEntry *e;
15     gchar *txt;
16     
17     g_assert(s);
18     g_assert(k);
19     g_assert(i);
20     g_assert(a);
21
22     g_message("Handling query: %s", txt = flx_key_to_string(k));
23     g_free(txt);
24
25     flx_packet_scheduler_incoming_query(i->scheduler, k);
26
27     if (k->type == FLX_DNS_TYPE_ANY) {
28
29         /* Handle ANY query */
30         
31         for (e = s->entries; e; e = e->entry_next)
32             if (flx_key_pattern_match(k, e->record->key))
33                 if (flx_interface_match(i, e->interface, e->protocol))
34                     flx_interface_post_response(i, a, e->record, FALSE);
35     } else {
36
37         /* Handle all other queries */
38         
39         for (e = g_hash_table_lookup(s->rrset_by_key, k); e; e = e->by_key_next)
40             if (flx_interface_match(i, e->interface, e->protocol))
41                 flx_interface_post_response(i, a, e->record, FALSE);
42     }
43 }
44
45 static void handle_query(flxServer *s, flxDnsPacket *p, flxInterface *i, const flxAddress *a) {
46     guint n;
47     
48     g_assert(s);
49     g_assert(p);
50     g_assert(i);
51     g_assert(a);
52
53     for (n = flx_dns_packet_get_field(p, DNS_FIELD_QDCOUNT); n > 0; n --) {
54         flxKey *key;
55
56         if (!(key = flx_dns_packet_consume_key(p))) {
57             g_warning("Packet too short");
58             return;
59         }
60
61         handle_query_key(s, key, i, a);
62         flx_key_unref(key);
63     }
64
65     /* Known Answer Suppresion */
66     for (n = flx_dns_packet_get_field(p, DNS_FIELD_ANCOUNT); n > 0; n --) {
67         flxRecord *record;
68         gboolean unique = FALSE;
69
70         if (!(record = flx_dns_packet_consume_record(p, &unique))) {
71             g_warning("Packet too short (2)");
72             return;
73         }
74
75         flx_packet_scheduler_incoming_known_answer(i->scheduler, record, a);
76         flx_record_unref(record);
77     }
78 }
79
80 static void handle_response(flxServer *s, flxDnsPacket *p, flxInterface *i, const flxAddress *a) {
81     guint n;
82     
83     g_assert(s);
84     g_assert(p);
85     g_assert(i);
86     g_assert(a);
87     
88     for (n = flx_dns_packet_get_field(p, DNS_FIELD_ANCOUNT) +
89              flx_dns_packet_get_field(p, DNS_FIELD_ARCOUNT); n > 0; n--) {
90         flxRecord *record;
91         gboolean cache_flush = FALSE;
92         gchar *txt;
93         
94         if (!(record = flx_dns_packet_consume_record(p, &cache_flush))) {
95             g_warning("Packet too short (3)");
96             return;
97         }
98
99         if (record->key->type == FLX_DNS_TYPE_ANY)
100             continue;
101         
102         g_message("Handling response: %s", txt = flx_record_to_string(record));
103         g_free(txt);
104         
105         flx_cache_update(i->cache, record, cache_flush, a);
106         
107         flx_packet_scheduler_incoming_response(i->scheduler, record);
108         flx_record_unref(record);
109     }
110 }
111
112 static void dispatch_packet(flxServer *s, flxDnsPacket *p, struct sockaddr *sa, gint iface, gint ttl) {
113     flxInterface *i;
114     flxAddress a;
115     
116     g_assert(s);
117     g_assert(p);
118     g_assert(sa);
119     g_assert(iface > 0);
120
121     g_message("new packet recieved.");
122
123     if (!(i = flx_interface_monitor_get_interface(s->monitor, iface, sa->sa_family))) {
124         g_warning("Recieved packet from invalid interface.");
125         return;
126     }
127
128     if (ttl != 255) {
129         g_warning("Recieved packet with invalid TTL on interface '%s.%i'.", i->hardware->name, i->protocol);
130         return;
131     }
132
133     if (sa->sa_family == AF_INET6) {
134         static const unsigned char ipv4_in_ipv6[] = {
135             0x00, 0x00, 0x00, 0x00,
136             0x00, 0x00, 0x00, 0x00,
137             0xFF, 0xFF, 0xFF, 0xFF };
138
139         if (memcmp(((struct sockaddr_in6*) sa)->sin6_addr.s6_addr, ipv4_in_ipv6, sizeof(ipv4_in_ipv6)) == 0) {
140
141             /* This is an IPv4 address encapsulated in IPv6, so let's ignore it. */
142             return;
143         }
144     }
145
146     if (flx_dns_packet_check_valid(p) < 0) {
147         g_warning("Recieved invalid packet.");
148         return;
149     }
150
151     flx_address_from_sockaddr(sa, &a);
152
153     if (flx_dns_packet_is_query(p)) {
154
155         if (flx_dns_packet_get_field(p, DNS_FIELD_QDCOUNT) == 0 ||
156             flx_dns_packet_get_field(p, DNS_FIELD_ARCOUNT) != 0 ||
157             flx_dns_packet_get_field(p, DNS_FIELD_NSCOUNT) != 0) {
158             g_warning("Invalid query packet.");
159             return;
160         }
161                 
162         handle_query(s, p, i, &a);    
163         g_message("Handled query");
164     } else {
165         if (flx_dns_packet_get_field(p, DNS_FIELD_QDCOUNT) != 0 ||
166             flx_dns_packet_get_field(p, DNS_FIELD_ANCOUNT) == 0 ||
167             flx_dns_packet_get_field(p, DNS_FIELD_NSCOUNT) != 0) {
168             g_warning("Invalid response packet.");
169             return;
170         }
171
172         handle_response(s, p, i, &a);
173         g_message("Handled response");
174     }
175 }
176
177 static gboolean work(flxServer *s) {
178     struct sockaddr_in6 sa6;
179     struct sockaddr_in sa;
180     flxDnsPacket *p;
181     gint iface = -1;
182     guint8 ttl;
183         
184     g_assert(s);
185
186     if (s->pollfd_ipv4.revents & G_IO_IN) {
187         if ((p = flx_recv_dns_packet_ipv4(s->fd_ipv4, &sa, &iface, &ttl))) {
188             dispatch_packet(s, p, (struct sockaddr*) &sa, iface, ttl);
189             flx_dns_packet_free(p);
190         }
191     }
192
193     if (s->pollfd_ipv6.revents & G_IO_IN) {
194         if ((p = flx_recv_dns_packet_ipv6(s->fd_ipv6, &sa6, &iface, &ttl))) {
195             dispatch_packet(s, p, (struct sockaddr*) &sa6, iface, ttl);
196             flx_dns_packet_free(p);
197         }
198     }
199
200     return TRUE;
201 }
202
203 static gboolean prepare_func(GSource *source, gint *timeout) {
204     g_assert(source);
205     g_assert(timeout);
206     
207     *timeout = -1;
208     return FALSE;
209 }
210
211 static gboolean check_func(GSource *source) {
212     flxServer* s;
213     g_assert(source);
214
215     s = *((flxServer**) (((guint8*) source) + sizeof(GSource)));
216     g_assert(s);
217     
218     return (s->pollfd_ipv4.revents | s->pollfd_ipv6.revents) & (G_IO_IN | G_IO_HUP | G_IO_ERR);
219 }
220
221 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
222     flxServer* s;
223     g_assert(source);
224
225     s = *((flxServer**) (((guint8*) source) + sizeof(GSource)));
226     g_assert(s);
227     
228     return work(s);
229 }
230
231 static void add_default_entries(flxServer *s) {
232     gint length = 0;
233     struct utsname utsname;
234     gchar *hinfo;
235     flxAddress a;
236     flxRecord *r;
237     
238     g_assert(s);
239     
240     /* Fill in HINFO rr */
241     r = flx_record_new_full(s->hostname, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_HINFO);
242     uname(&utsname);
243     r->data.hinfo.cpu = g_strdup(g_strup(utsname.machine));
244     r->data.hinfo.os = g_strdup(g_strup(utsname.sysname));
245     flx_server_add(s, 0, 0, AF_UNSPEC, TRUE, r);
246     flx_record_unref(r);
247
248     /* Add localhost entries */
249     flx_address_parse("127.0.0.1", AF_INET, &a);
250     flx_server_add_address(s, 0, 0, AF_UNSPEC, TRUE, "localhost", &a);
251
252     flx_address_parse("::1", AF_INET6, &a);
253     flx_server_add_address(s, 0, 0, AF_UNSPEC, TRUE, "ip6-localhost", &a);
254 }
255
256 flxServer *flx_server_new(GMainContext *c) {
257     gchar *hn, *e;
258     flxServer *s;
259     
260     static GSourceFuncs source_funcs = {
261         prepare_func,
262         check_func,
263         dispatch_func,
264         NULL,
265         NULL,
266         NULL
267     };
268
269     s = g_new(flxServer, 1);
270
271     s->fd_ipv4 = flx_open_socket_ipv4();
272     s->fd_ipv6 = flx_open_socket_ipv6();
273     
274     if (s->fd_ipv6 < 0 && s->fd_ipv4 < 0) {
275         g_critical("Failed to create sockets.\n");
276         g_free(s);
277         return NULL;
278     }
279
280     if (s->fd_ipv4 < 0)
281         g_message("Failed to create IPv4 socket, proceeding in IPv6 only mode");
282     else if (s->fd_ipv6 < 0)
283         g_message("Failed to create IPv6 socket, proceeding in IPv4 only mode");
284     
285     if (c)
286         g_main_context_ref(s->context = c);
287     else
288         s->context = g_main_context_default();
289     
290     s->current_id = 1;
291
292     FLX_LLIST_HEAD_INIT(flxServerEntry, s->entries);
293     s->rrset_by_id = g_hash_table_new(g_int_hash, g_int_equal);
294     s->rrset_by_key = g_hash_table_new((GHashFunc) flx_key_hash, (GEqualFunc) flx_key_equal);
295
296     FLX_LLIST_HEAD_INIT(flxSubscription, s->subscriptions);
297     s->subscription_hashtable = g_hash_table_new((GHashFunc) flx_key_hash, (GEqualFunc) flx_key_equal);
298
299     s->monitor = flx_interface_monitor_new(s);
300     s->time_event_queue = flx_time_event_queue_new(s->context);
301     
302     /* Get host name */
303     hn = flx_get_host_name();
304     if ((e = strchr(hn, '.')))
305         *e = 0;
306
307     s->hostname = g_strdup_printf("%s.local.", hn);
308     g_free(hn);
309
310     add_default_entries(s);
311
312     s->source = g_source_new(&source_funcs, sizeof(GSource) + sizeof(flxServer*));
313     *((flxServer**) (((guint8*) s->source) + sizeof(GSource))) = s;
314
315     memset(&s->pollfd_ipv4, 0, sizeof(s->pollfd_ipv4));
316     s->pollfd_ipv4.fd = s->fd_ipv4;
317     s->pollfd_ipv4.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
318     g_source_add_poll(s->source, &s->pollfd_ipv4);
319     
320     memset(&s->pollfd_ipv6, 0, sizeof(s->pollfd_ipv6));
321     s->pollfd_ipv6.fd = s->fd_ipv6;
322     s->pollfd_ipv6.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
323     g_source_add_poll(s->source, &s->pollfd_ipv6);
324
325     g_source_attach(s->source, s->context);
326     
327     return s;
328 }
329
330 void flx_server_free(flxServer* s) {
331     g_assert(s);
332
333     flx_interface_monitor_free(s->monitor);
334     
335     flx_server_remove(s, 0);
336
337     while (s->subscriptions)
338         flx_subscription_free(s->subscriptions);
339     g_hash_table_destroy(s->subscription_hashtable);
340     
341     g_hash_table_destroy(s->rrset_by_id);
342     g_hash_table_destroy(s->rrset_by_key);
343
344     flx_time_event_queue_free(s->time_event_queue);
345
346     if (s->fd_ipv4 >= 0)
347         close(s->fd_ipv4);
348     if (s->fd_ipv6 >= 0)
349         close(s->fd_ipv6);
350     
351     g_free(s->hostname);
352
353     g_source_destroy(s->source);
354     g_source_unref(s->source);
355     g_main_context_unref(s->context);
356
357     g_free(s);
358 }
359
360 gint flx_server_get_next_id(flxServer *s) {
361     g_assert(s);
362
363     return s->current_id++;
364 }
365
366 void flx_server_add(
367     flxServer *s,
368     gint id,
369     gint interface,
370     guchar protocol,
371     gboolean unique,
372     flxRecord *r) {
373     
374     flxServerEntry *e, *t;
375     g_assert(s);
376     g_assert(r);
377
378     g_assert(r->key->type != FLX_DNS_TYPE_ANY);
379
380     e = g_new(flxServerEntry, 1);
381     e->record = flx_record_ref(r);
382     e->id = id;
383     e->interface = interface;
384     e->protocol = protocol;
385     e->unique = unique;
386
387     FLX_LLIST_HEAD_INIT(flxAnnouncement, e->announcements);
388
389     FLX_LLIST_PREPEND(flxServerEntry, entry, s->entries, e);
390
391     /* Insert into hash table indexed by id */
392     t = g_hash_table_lookup(s->rrset_by_id, &e->id);
393     FLX_LLIST_PREPEND(flxServerEntry, by_id, t, e);
394     g_hash_table_replace(s->rrset_by_id, &e->id, t);
395     
396     /* Insert into hash table indexed by name */
397     t = g_hash_table_lookup(s->rrset_by_key, e->record->key);
398     FLX_LLIST_PREPEND(flxServerEntry, by_key, t, e);
399     g_hash_table_replace(s->rrset_by_key, e->record->key, t);
400
401     flx_announce_entry(s, e);
402 }
403 const flxRecord *flx_server_iterate(flxServer *s, gint id, void **state) {
404     flxServerEntry **e = (flxServerEntry**) state;
405     g_assert(s);
406     g_assert(e);
407
408     if (e)
409         *e = id > 0 ? (*e)->by_id_next : (*e)->entry_next;
410     else
411         *e = id > 0 ? g_hash_table_lookup(s->rrset_by_id, &id) : s->entries;
412         
413     if (!*e)
414         return NULL;
415
416     return flx_record_ref((*e)->record);
417 }
418
419 static void free_entry(flxServer*s, flxServerEntry *e) {
420     flxServerEntry *t;
421     
422     g_assert(e);
423
424     flx_goodbye_entry(s, e, TRUE);
425
426     /* Remove from linked list */
427     FLX_LLIST_REMOVE(flxServerEntry, entry, s->entries, e);
428
429     /* Remove from hash table indexed by id */
430     t = g_hash_table_lookup(s->rrset_by_id, &e->id);
431     FLX_LLIST_REMOVE(flxServerEntry, by_id, t, e);
432     if (t)
433         g_hash_table_replace(s->rrset_by_id, &t->id, t);
434     else
435         g_hash_table_remove(s->rrset_by_id, &e->id);
436     
437     /* Remove from hash table indexed by name */
438     t = g_hash_table_lookup(s->rrset_by_key, e->record->key);
439     FLX_LLIST_REMOVE(flxServerEntry, by_key, t, e);
440     if (t)
441         g_hash_table_replace(s->rrset_by_key, t->record->key, t);
442     else
443         g_hash_table_remove(s->rrset_by_key, e->record->key);
444
445     flx_record_unref(e->record);
446     g_free(e);
447 }
448
449 void flx_server_remove(flxServer *s, gint id) {
450     g_assert(s);
451
452     if (id <= 0) {
453         while (s->entries)
454             free_entry(s, s->entries);
455     } else {
456         flxServerEntry *e;
457
458         while ((e = g_hash_table_lookup(s->rrset_by_id, &id)))
459             free_entry(s, e);
460     }
461 }
462
463 void flx_server_dump(flxServer *s, FILE *f) {
464     flxServerEntry *e;
465     g_assert(s);
466     g_assert(f);
467
468     fprintf(f, "\n;;; ZONE DUMP FOLLOWS ;;;\n");
469
470     for (e = s->entries; e; e = e->entry_next) {
471         gchar *t;
472
473         t = flx_record_to_string(e->record);
474         fprintf(f, "%s\n", t);
475         g_free(t);
476     }
477
478     flx_dump_caches(s->monitor, f);
479 }
480
481 void flx_server_add_ptr(
482     flxServer *s,
483     gint id,
484     gint interface,
485     guchar protocol,
486     gboolean unique,
487     const gchar *name,
488     const gchar *dest) {
489
490     flxRecord *r;
491
492     g_assert(dest);
493
494     r = flx_record_new_full(name ? name : s->hostname, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_PTR);
495     r->data.ptr.name = flx_normalize_name(dest);
496     flx_server_add(s, id, interface, protocol, unique, r);
497     flx_record_unref(r);
498
499 }
500
501 void flx_server_add_address(
502     flxServer *s,
503     gint id,
504     gint interface,
505     guchar protocol,
506     gboolean unique,
507     const gchar *name,
508     flxAddress *a) {
509
510     gchar *n = NULL;
511     g_assert(s);
512     g_assert(a);
513
514     name = name ? (n = flx_normalize_name(name)) : s->hostname;
515     
516     if (a->family == AF_INET) {
517         gchar *reverse;
518         flxRecord  *r;
519
520         r = flx_record_new_full(name, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_A);
521         r->data.a.address = a->data.ipv4;
522         flx_server_add(s, id, interface, protocol, unique, r);
523         flx_record_unref(r);
524         
525         reverse = flx_reverse_lookup_name_ipv4(&a->data.ipv4);
526         g_assert(reverse);
527         flx_server_add_ptr(s, id, interface, protocol, unique, reverse, name);
528         g_free(reverse);
529         
530     } else {
531         gchar *reverse;
532         flxRecord *r;
533             
534         r = flx_record_new_full(name, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_AAAA);
535         r->data.aaaa.address = a->data.ipv6;
536         flx_server_add(s, id, interface, protocol, unique, r);
537         flx_record_unref(r);
538
539         reverse = flx_reverse_lookup_name_ipv6_arpa(&a->data.ipv6);
540         g_assert(reverse);
541         flx_server_add_ptr(s, id, interface, protocol, unique, reverse, name);
542         g_free(reverse);
543     
544         reverse = flx_reverse_lookup_name_ipv6_int(&a->data.ipv6);
545         g_assert(reverse);
546         flx_server_add_ptr(s, id, interface, protocol, unique, reverse, name);
547         g_free(reverse);
548     }
549     
550     g_free(n);
551 }
552
553 void flx_server_add_text_va(
554     flxServer *s,
555     gint id,
556     gint interface,
557     guchar protocol,
558     gboolean unique,
559     const gchar *name,
560     va_list va) {
561
562     flxRecord *r;
563     
564     g_assert(s);
565     
566     r = flx_record_new_full(name ? name : s->hostname, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_TXT);
567     r->data.txt.string_list = flx_string_list_new_va(va);
568     flx_server_add(s, id, interface, protocol, unique, r);
569     flx_record_unref(r);
570 }
571
572 void flx_server_add_text(
573     flxServer *s,
574     gint id,
575     gint interface,
576     guchar protocol,
577     gboolean unique,
578     const gchar *name,
579     ...) {
580
581     va_list va;
582     
583     g_assert(s);
584
585     va_start(va, name);
586     flx_server_add_text_va(s, id, interface, protocol, unique, name, va);
587     va_end(va);
588 }
589
590 static void escape_service_name(gchar *d, guint size, const gchar *s) {
591     g_assert(d);
592     g_assert(size);
593     g_assert(s);
594
595     while (*s && size >= 2) {
596         if (*s == '.' || *s == '\\') {
597             if (size < 3)
598                 break;
599
600             *(d++) = '\\';
601             size--;
602         }
603             
604         *(d++) = *(s++);
605         size--;
606     }
607
608     g_assert(size > 0);
609     *(d++) = 0;
610 }
611
612
613 void flx_server_add_service_va(
614     flxServer *s,
615     gint id,
616     gint interface,
617     guchar protocol,
618     const gchar *type,
619     const gchar *name,
620     const gchar *domain,
621     const gchar *host,
622     guint16 port,
623     va_list va) {
624
625     gchar ptr_name[256], svc_name[256], ename[64], enum_ptr[256];
626     flxRecord *r;
627     
628     g_assert(s);
629     g_assert(type);
630     g_assert(name);
631
632     escape_service_name(ename, sizeof(ename), name);
633
634     if (domain) {
635         while (domain[0] == '.')
636             domain++;
637     } else
638         domain = "local";
639
640     if (!host)
641         host = s->hostname;
642
643     snprintf(ptr_name, sizeof(ptr_name), "%s.%s", type, domain);
644     snprintf(svc_name, sizeof(svc_name), "%s.%s.%s", ename, type, domain);
645     
646     flx_server_add_ptr(s, id, interface, protocol, FALSE, ptr_name, svc_name);
647
648     r = flx_record_new_full(svc_name, FLX_DNS_CLASS_IN, FLX_DNS_TYPE_SRV);
649     r->data.srv.priority = 0;
650     r->data.srv.weight = 0;
651     r->data.srv.port = port;
652     r->data.srv.name = flx_normalize_name(host);
653     flx_server_add(s, id, interface, protocol, TRUE, r);
654     flx_record_unref(r);
655
656     flx_server_add_text_va(s, id, interface, protocol, FALSE, svc_name, va);
657
658     snprintf(enum_ptr, sizeof(enum_ptr), "_services._dns-sd._udp.%s", domain);
659     flx_server_add_ptr(s, id, interface, protocol, FALSE, enum_ptr, ptr_name);
660 }
661
662 void flx_server_add_service(
663     flxServer *s,
664     gint id,
665     gint interface,
666     guchar protocol,
667     const gchar *type,
668     const gchar *name,
669     const gchar *domain,
670     const gchar *host,
671     guint16 port,
672     ... ){
673
674     va_list va;
675     
676     g_assert(s);
677     g_assert(type);
678     g_assert(name);
679
680     va_start(va, port);
681     flx_server_add_service_va(s, id, interface, protocol, type, name, domain, host, port, va);
682     va_end(va);
683 }
684
685 static void post_query_callback(flxInterfaceMonitor *m, flxInterface *i, gpointer userdata) {
686     flxKey *k = userdata;
687
688     g_assert(m);
689     g_assert(i);
690     g_assert(k);
691
692     flx_interface_post_query(i, k, FALSE);
693 }
694
695 void flx_server_post_query(flxServer *s, gint interface, guchar protocol, flxKey *key) {
696     g_assert(s);
697     g_assert(key);
698
699     flx_interface_monitor_walk(s->monitor, interface, protocol, post_query_callback, key);
700 }
701
702 static void post_response_callback(flxInterfaceMonitor *m, flxInterface *i, gpointer userdata) {
703     flxRecord *r = userdata;
704
705     g_assert(m);
706     g_assert(i);
707     g_assert(r);
708
709     flx_interface_post_response(i, NULL, r, FALSE);
710 }
711
712 void flx_server_post_response(flxServer *s, gint interface, guchar protocol, flxRecord *record) {
713     g_assert(s);
714     g_assert(record);
715
716     flx_interface_monitor_walk(s->monitor, interface, protocol, post_response_callback, record);
717 }