summaryrefslogtreecommitdiff
path: root/src/lacdns-query.c
blob: 83b788108eacd7d5d1c87fbc8a7bf59a3c1f7dc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- */

/*  Lac - Library for asynchronous communication
 *  Copyright (C) 2002, 2003  Søren Sandmann (sandmann@daimi.au.dk)
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the 
 *  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *  Boston, MA  02111-1307, USA.
 */

#include "lacdns-nameserver.h"
#include "lacdns-cache.h"
#include "lacdns-config.h"
#include "lacdns-query.h"
#include <string.h>

typedef struct DnsQuery DnsQuery;
typedef struct Callback Callback;

struct Callback {
    DnsQueryEventFunc   func;
    gpointer            data;
};

struct DnsQuery {
    GList *             callbacks;

    /* query description */
    RRType              type;
    GQueue *            all_names;
    GQueue *            all_servers;

    /* uncachable records */
    GQueue *            uncachable_records;
    
    /* query state */
    GQueue *            untried_names;
    DomainName *        current_name;
    GQueue *            tried_names;

    GQueue *            untried_servers;
    NameServer *        current_server;
    GQueue *            tried_servers;

    gint                current_id;     /* Id of the latest question we
                                         * asked any server.
                                         */
    
    gint                attempts;	/* how many trips through the list
					 * of servers we have made
					 */

    gboolean            use_tcp;
    gint                timeout;

    gint                ref_count;
};

static gboolean  dns_query_next_name    (DnsQuery *query);
static gboolean  dns_query_next_server  (DnsQuery *query);
static void      dns_query_ask_server   (DnsQuery *query);
static gboolean  dns_query_cache_lookup (DnsQuery *query);
static void      dns_query_unref (DnsQuery *query);
static DnsQuery *dns_query_ref (DnsQuery *query);

static GHashTable *outstanding_queries = NULL;

static void
do_callback (DnsQuery *query, const DnsQueryEvent *event)
{
    GList *list;
    ResourceRecord *rr;

    g_assert (g_hash_table_remove (outstanding_queries, query));

#if 0
    g_print ("callback on %p\n", query);
#endif

    g_assert (!g_hash_table_lookup (outstanding_queries, query));
    
    if (query->timeout)
    {
        g_source_remove (query->timeout);
        query->timeout = 0;
    }
    
    /* Delete uncachable records from the cache before calling the user.
     * See comment in analyze_normal_message()
     */
    while ((rr = g_queue_pop_head (query->uncachable_records)))
        cache_delete_rdata (rr->name, rr->rdata);

    /* call user */
    for (list = query->callbacks; list != NULL; list = list->next)
    {
        Callback *callback = list->data;
        
        callback->func (event, callback->data);
    }

#if 0
    g_print ("end callback on %p\n", query);
#endif
    
    dns_query_unref (query);
}

static void
emit_error (DnsQuery *query, const GError *err)
{
    DnsQueryEvent event;

    event.type = DNS_QUERY_EVENT_ERROR;
    event.error.err = err;
    
    do_callback (query, &event);
}

static void
emit_results (DnsQuery *query, const GList *results)
{
    DnsQueryEvent event;

    event.type = DNS_QUERY_EVENT_RESULTS;
    event.results.results = results;

    do_callback (query, &event);
}

static void
emit_no_data (DnsQuery *query)
{
    DnsQueryEvent event;

    event.type = DNS_QUERY_EVENT_NO_DATA;

    do_callback (query, &event);
}

static void
emit_no_such_name (DnsQuery *query)
{
    DnsQueryEvent event;

    if (dns_query_next_name (query))
    {
	if (!dns_query_cache_lookup (query))
        {
            /* We need to delete the list of uncachable records
             * here since as soon as we return from analyze_reply()
             * the content will be freed, and this query may
             * survive longer than that.
             *
             * In the the other emit() functions we call
             * do_callback() which takes care of the problem.
             */
            while (g_queue_pop_head (query->uncachable_records))
                ;
            
            dns_query_ask_server (query);
        }
	
	return;
    }

    event.type = DNS_QUERY_EVENT_NO_SUCH_NAME;

    do_callback (query, &event);
}

static void
insert_in_cache (ResourceRecord *rr,
                 GQueue         *uncachable_records)
{
    /* FIXME: currently, we simply ignore cname cycles.
     * Maybe we shouldn't (or maybe the cache itself should
     * handle cname cycles
     */
    if (rr->time_to_live == 0)
    {
	/* Make sure the cache won't delete the record
	 * immediately.
	 */
	rr->time_to_live = 1000;

        g_queue_push_tail (uncachable_records, rr);
    }

    cache_insert_positive (rr, NULL);
}

static void
analyze_normal_message (const Message *message, DnsQuery *query)
{
    GList *list;
    
    /* The basic idea here is to insert everything in the cache
     * and then do a dns_query_cache_lookup()
     *
     * However, records with time-to-live == 0 must not be cached.
     * To make sure we don't end up with uncacheable records in the
     * cache, we maintain a separate list of records with ttl = 0.
     * Then when the dns_query_cache_lookup() is done, we delete
     * those records from the cache.
     *
     * To make sure we don't callback to the user with uncachable
     * records in the cache, the list is stored in the query
     * and the records are removed from the cache by do_callback()
     * before actually calling out the user. Yeah, this could use
     * some reorganization ...
     */
    gchar  *error_msg = NULL;

    g_return_if_fail (query->current_name != NULL);
    
    for (list = message->answer_records->head; list; list = list->next)
        insert_in_cache (list->data, query->uncachable_records);
    
    for (list = message->authority_records->head; list; list = list->next)
        insert_in_cache (list->data, query->uncachable_records);
    
    for (list = message->additional_records->head; list; list = list->next)
        insert_in_cache (list->data, query->uncachable_records);
    
    switch (message->response_code)
    {
    case NO_ERROR:
        if (!dns_query_cache_lookup (query))
        {
            RData *soa = cache_lookup_soa (query->current_name);
            if (soa)
            {
                cache_insert_no_data (
                    query->current_name, query->type, soa->u.soa.minimum);
                rdata_free (soa);
            }
            
            emit_no_data (query);
        }
        break;
        
    case NAME_ERROR:
    {
        RData *soa = cache_lookup_soa (query->current_name);
        if (soa)
        {
            cache_insert_no_such_name (query->current_name, soa->u.soa.minimum);
            rdata_free (soa);
        }
        
        emit_no_such_name (query);
        break;
    }
        
    case FORMAT_ERROR:
        error_msg  = g_strdup ("Server reported \"format error\" (this is "
                               "probably a bug in Lac)");
        break;
        
    case SERVER_FAILURE:
        error_msg  = g_strdup ("Server failed");
        break;
        
    case NOT_IMPLEMENTED:
        error_msg  = g_strdup ("Server reported \"not implemented\"");
        break;
        
    case REFUSED:
        error_msg  = g_strdup ("Server refused service");
        break;
        
    default:
        error_msg  = g_strdup_printf ("Unknown response code received "
                                      "from server: %d",
                                      message->response_code);
        break;
    }
    
    if (error_msg)
    {
        GError *dns_error =
            g_error_new (LAC_DNS_ERROR, LAC_DNS_ERROR_SERVER_FAILED,
                         error_msg);
        emit_error (query, dns_error);
        g_error_free (dns_error);
        g_free (error_msg);
    }
}

static void
analyze_reply (gint id, const Message *message, gpointer data, const GError *err)
{
    DnsQuery *query = data;

    /* If the original query is no longer in the table of outstanding queries
     * it means that we already called back to the user, so we can't do
     * anything useful with this reply.
     *
     * FIXME: hmm, we *could* try to cache it. The data should be good enough ...
     */
    if (query == g_hash_table_lookup (outstanding_queries, query))
    {
        /* ignore error replies to old questions */
        if (err && id == query->current_id)
        {
            if (dns_query_next_server (query))
                dns_query_ask_server (query);
            else
                emit_error (query, err);
        }
        else if (message->truncated && !query->use_tcp)
        {
            /* This is the right thing to do even if this is a reply
             * to an old query. We assume the data is basically OK (just
             * slow to arrive), so any UDP reply will be truncated. Thus,
             * we might as well try a TCP connection immediately.
             */
            query->use_tcp = TRUE;
            
            dns_query_ask_server (query);
        }
        else
        {
            /* if we got a tcp reply with "truncated" set to
             * TRUE, we'll assume that the server set this
             * bit by mistake and that the reply is otherwise
             * good enough.
             */
            
            analyze_normal_message (message, query);
        }
    }
    else
    {
        g_assert (query->timeout == 0);
    }
    
    dns_query_unref (query);
}

static gboolean
handle_timeout (gpointer data)
{
    DnsQuery *query = data;

    query->timeout = 0;
    
    if (dns_query_next_server (query))
    {
        dns_query_ask_server (query);
    }
    else
    {
        GError *err = g_error_new (
            LAC_DNS_ERROR, LAC_DNS_ERROR_TIMEOUT,
            "No servers could be reached");
        
        emit_error (query, err);

        g_error_free (err);
    }

    return FALSE;
}

static DomainName *
canonicalize_name (const DomainName *name)
{
    DomainName *result = NULL;
    RData *cname = cache_lookup_cname (name);
    
    if (cname)
    {
        if (!(result = canonicalize_name (cname->u.cname.name)))
            result = domain_name_copy (cname->u.cname.name);
        
        rdata_free (cname);
    }

    return result;
}

static gboolean
dns_query_cache_lookup (DnsQuery *query)
{
    CacheResult *result;

    g_return_val_if_fail (query->current_name != NULL, FALSE);
    
    result = cache_lookup_recursive (query->current_name, query->type);

    if (result->type == CACHE_NOTHING_KNOWN ||
        result->type == CACHE_NAME_EXISTS)
    {
        DomainName *cname = canonicalize_name (query->current_name);
        
        if (cname)
        {
            g_queue_push_head (query->untried_names, cname);

            dns_query_next_name (query);
            dns_query_ask_server (query);

            return TRUE;
        }
            
        cache_result_free (result);
        return FALSE;
    }

#if 0
    g_print ("data in cache\n");
#endif
    
    if (result->type == CACHE_NO_DATA)
        emit_no_data (query);
    else if (result->type == CACHE_DATA_FOUND)
        emit_results (query, result->records);
    else if (result->type == CACHE_NO_SUCH_NAME)
        emit_no_such_name (query);

    cache_result_free (result);
    return TRUE;
}

static void
dns_query_ask_server (DnsQuery *query)
{
    Message *question;

    g_return_if_fail (query != NULL);
    g_return_if_fail (query->current_server != NULL);

    if (query->timeout)
    {
        g_source_remove (query->timeout);
        query->timeout = 0;
    }
    
    question = message_new_question (query->current_name, query->type);
    query->current_id = question->id;

    query->timeout = g_timeout_add (
        dns_config_get_timeout (), handle_timeout, query);
    
    name_server_query (query->current_server, query->use_tcp,
                       question, analyze_reply, dns_query_ref (query));

    message_free (question);
}

static gboolean
dns_query_next_server (DnsQuery *query)
{
    g_return_val_if_fail (query != NULL, FALSE);

    if (query->current_server)
	g_queue_push_tail (query->tried_servers, query->current_server);
    
    if (g_queue_is_empty (query->untried_servers))
    {
	++query->attempts;

	if (query->attempts < dns_config_get_attempts())
	{
	    GQueue *tmp = query->tried_servers;
	    query->tried_servers = query->untried_servers;
	    query->untried_servers = tmp;
	}
    }

    query->current_server = g_queue_pop_head (query->untried_servers);

    if (!query->current_server)
	return FALSE;

    return TRUE;
}

static gboolean
dns_query_next_name (DnsQuery *query)
{
    query->current_name = g_queue_pop_head (query->untried_names);

    if (!query->current_name)
	return FALSE;

    query->attempts = 0;
    return TRUE;
}

static guint
count_dots (const gchar *s)
{
    guint n_dots = 0;
    
    while (*s)
    {
	if (*s++ == '.')
	    n_dots++;
    }

    return n_dots;
}

static GQueue *
build_names (const gchar *domain_str)
{
    GQueue *search_list = dns_config_get_search_list();
    GQueue *try_names;
    DomainName *absolute_name;
    guint config_n_dots;
    guint dots;
    GList *list;

    g_return_val_if_fail (domain_str != NULL, NULL);

    try_names = g_queue_new ();

    absolute_name = domain_name_new_from_str (domain_str);

    g_assert (absolute_name);
    
    config_n_dots = dns_config_get_n_dots ();
    dots = count_dots (domain_str);

    /* if input contains more than the configured n_dots,
     * try as absolute name before search list ...
     */
    if (dots >= config_n_dots)
	g_queue_push_tail (try_names, absolute_name);
    
    /* ignore search list if input ends in a dot
     */
    if (search_list &&
	domain_str[strlen (domain_str) - 1] != '.')
    {
	for (list = search_list->head; list; list = list->next)
	{
	    gchar *search_path = list->data;
	    gchar *str;
	    DomainName *name;
	    
	    str = g_strconcat (domain_str, ".", search_path, NULL);
	    
	    name = domain_name_new_from_str (str);
            if (name)
                g_queue_push_tail (try_names, name);
	    
	    g_free (str);
	}
    }
    
    /* ... otherwise try as absolute name after the search list
     */
    if (dots < config_n_dots)
	g_queue_push_tail (try_names, absolute_name);

    /* free search list */
    for (list = search_list->head; list != NULL; list = list->next)
        g_free (list->data);
    g_queue_free (search_list);
    
    g_assert (!g_queue_is_empty (try_names));
    return try_names;
}

static guint
dns_query_hash (gconstpointer data)
{
    const DnsQuery *query = data;
    guint hash;
    GList *list;

    hash = query->type;

    for (list = query->all_names->head; list != NULL; list = list->next)
        hash += domain_name_hash (list->data);

    for (list = query->all_servers->head; list != NULL; list = list->next)
        hash += g_direct_hash (list->data);

    return hash;
}

static gboolean
dns_query_equal (gconstpointer data1, gconstpointer data2)
{
    const DnsQuery *query1 = data1;
    const DnsQuery *query2 = data2;

    GList *list1, *list2;

    /* check that the queries are of the same type */
    if (query1->type != query2->type)
        return FALSE;

    /* check that the queries are trying the same names in the same order */
    if (query1->all_names->length != query2->all_names->length)
        return FALSE;

    list1 = query1->all_names->head;
    list2 = query2->all_names->head;
    while (list1 && list2)
    {
        DomainName *d1 = list1->data;
        DomainName *d2 = list2->data;
        
        if (!domain_name_equal (d1, d2))
            return FALSE;
            
        list1 = list1->next;
        list2 = list2->next;
    }

    /* check that the queries are trying the same servers in the same order */
    if (query1->all_servers->length != query2->all_servers->length)
        return FALSE;

    list1 = query1->all_servers->head;
    list2 = query2->all_servers->head;
    while (list1 && list2)
    {
        NameServer *n1 = list1->data;
        NameServer *n2 = list2->data;

        if (n1 != n2)
            return FALSE;

        list1 = list1->next;
        list2 = list2->next;
    }

    return TRUE;
}

static GQueue *
copy_queue (GQueue *queue)
{
    GQueue *copy = g_queue_new ();
    GList *list;

    for (list = queue->head; list != NULL; list = list->next)
        g_queue_push_tail (copy, list->data);

    return copy;
}

static void
dns_query_free (DnsQuery *query)
{
    GList *list;

    g_assert (g_queue_is_empty (query->uncachable_records));

    g_queue_free (query->uncachable_records);
    
    for (list = query->callbacks; list != NULL; list = list->next)
        g_free (list->data);
    g_list_free (query->callbacks);

    while (!g_queue_is_empty (query->all_names))
        domain_name_free (g_queue_pop_head (query->all_names));

    g_queue_free (query->all_names);
    g_queue_free (query->all_servers);

    g_queue_free (query->untried_names);
    g_queue_free (query->tried_names);
    
    g_queue_free (query->untried_servers);
    g_queue_free (query->tried_servers);

    g_free (query);
}

static void
dns_query_unref (DnsQuery *query)
{
    if (--query->ref_count == 0)
        dns_query_free (query);
}

static DnsQuery *
dns_query_ref (DnsQuery *query)
{
    ++query->ref_count;
    return query;
}

static gboolean
domain_is_well_formed (const gchar *domain)
{
    DomainName *dname = domain_name_new_from_str (domain);

    if (!dname)
        return FALSE;

    domain_name_free (dname);
    return TRUE;
}

/*
 * DnsQuery public functions
 */
void
dns_query (const gchar       *domain,
           RRType             type,
           DnsQueryEventFunc  func,
           gpointer           data)
{
    DnsQuery *query;
    DnsQuery *existing;
    Callback *callback;
    
    g_return_if_fail (domain != NULL);
    g_return_if_fail (strlen (domain) > 0);
    g_return_if_fail (func != NULL);

    if (!domain_is_well_formed (domain))
    {
        DnsQueryEvent event;
        
	GError *err = g_error_new (
	    LAC_DNS_ERROR, LAC_DNS_ERROR_MALFORMED_NAME,
	    "The string %s is not a valid domain name", domain);

        event.type = DNS_QUERY_EVENT_ERROR;
        event.error.err = err;

        func (&event, data);

        g_error_free (err);
        return;
    }
    
    if (!outstanding_queries)
    {
        outstanding_queries =
            g_hash_table_new (dns_query_hash, dns_query_equal);
    }
    
    query = g_new (DnsQuery, 1);

    query->type = type;
    query->all_servers = dns_config_get_servers ();
    query->all_names = build_names (domain);
    
    callback = g_new (Callback, 1);
    callback->func = func;
    callback->data = data;

    existing = g_hash_table_lookup (outstanding_queries, query);
    if (existing)
    {
#if 0
        g_print ("using existing (%p)\n", existing);
#endif
        existing->callbacks = g_list_prepend (existing->callbacks, callback);

        while (!g_queue_is_empty (query->all_names))
            domain_name_free (g_queue_pop_head (query->all_names));
        
        g_queue_free (query->all_names);
        g_queue_free (query->all_servers);

        g_free (query);
    }
    else
    {
        query->callbacks = g_list_prepend (NULL, callback);

        query->uncachable_records = g_queue_new ();
        
        query->untried_names = copy_queue (query->all_names);
        query->current_name = NULL;
        query->tried_names = g_queue_new();
        
        query->untried_servers = copy_queue (query->all_servers);
        query->current_server = NULL;
        query->tried_servers = g_queue_new();

        query->current_id = 0;
        query->attempts = 0;
        
        query->timeout = 0;

        query->use_tcp = FALSE;
        query->ref_count = 1;

        dns_query_next_name (query);
        dns_query_next_server (query);

#if 0
        g_print ("inserting %p\n", query);
#endif

        g_hash_table_insert (outstanding_queries, query, query);
        
        if (!dns_query_cache_lookup (query))
            dns_query_ask_server (query);
    }
}