+#include "subscribe.h"
+
+static void handle_query_key(flxServer *s, flxKey *k, flxInterface *i, const flxAddress *a) {
+ flxServerEntry *e;
+ gchar *txt;
+
+ g_assert(s);
+ g_assert(k);
+ g_assert(i);
+ g_assert(a);
+
+ g_message("Handling query: %s", txt = flx_key_to_string(k));
+ g_free(txt);
+
+ flx_packet_scheduler_incoming_query(i->scheduler, k);
+
+ if (k->type == FLX_DNS_TYPE_ANY) {
+
+ /* Handle ANY query */
+
+ for (e = s->entries; e; e = e->entry_next)
+ if (flx_key_pattern_match(k, e->record->key))
+ if (flx_interface_match(i, e->interface, e->protocol) && flx_entry_established(s, e, i))
+ flx_interface_post_response(i, a, e->record, e->flags & FLX_SERVER_ENTRY_UNIQUE, FALSE);
+ } else {
+
+ /* Handle all other queries */
+
+ for (e = g_hash_table_lookup(s->rrset_by_key, k); e; e = e->by_key_next)
+ if (flx_interface_match(i, e->interface, e->protocol) && flx_entry_established(s, e, i))
+ flx_interface_post_response(i, a, e->record, e->flags & FLX_SERVER_ENTRY_UNIQUE, FALSE);
+ }
+}
+
+static void handle_query(flxServer *s, flxDnsPacket *p, flxInterface *i, const flxAddress *a) {
+ guint n;
+
+ g_assert(s);
+ g_assert(p);
+ g_assert(i);
+ g_assert(a);
+
+ for (n = flx_dns_packet_get_field(p, FLX_DNS_FIELD_QDCOUNT); n > 0; n --) {
+ flxKey *key;
+
+ if (!(key = flx_dns_packet_consume_key(p))) {
+ g_warning("Packet too short");
+ return;
+ }
+
+ handle_query_key(s, key, i, a);
+ flx_key_unref(key);
+ }
+
+ /* Known Answer Suppresion */
+ for (n = flx_dns_packet_get_field(p, FLX_DNS_FIELD_ANCOUNT); n > 0; n --) {
+ flxRecord *record;
+ gboolean unique = FALSE;
+
+ if (!(record = flx_dns_packet_consume_record(p, &unique))) {
+ g_warning("Packet too short (2)");
+ return;
+ }
+
+ flx_packet_scheduler_incoming_known_answer(i->scheduler, record, a);
+ flx_record_unref(record);
+ }
+}
+
+static void handle_response(flxServer *s, flxDnsPacket *p, flxInterface *i, const flxAddress *a) {
+ guint n;
+
+ g_assert(s);
+ g_assert(p);
+ g_assert(i);
+ g_assert(a);
+
+ for (n = flx_dns_packet_get_field(p, FLX_DNS_FIELD_ANCOUNT) +
+ flx_dns_packet_get_field(p, FLX_DNS_FIELD_ARCOUNT); n > 0; n--) {
+ flxRecord *record;
+ gboolean cache_flush = FALSE;
+ gchar *txt;
+
+ if (!(record = flx_dns_packet_consume_record(p, &cache_flush))) {
+ g_warning("Packet too short (3)");
+ return;
+ }
+
+ if (record->key->type == FLX_DNS_TYPE_ANY)
+ continue;
+
+ g_message("Handling response: %s", txt = flx_record_to_string(record));
+ g_free(txt);
+
+ flx_cache_update(i->cache, record, cache_flush, a);
+
+ flx_packet_scheduler_incoming_response(i->scheduler, record);
+ flx_record_unref(record);
+ }
+}